可以写出相关代码不
时间: 2024-02-11 11:05:29 浏览: 72
当然可以,以下是 Camera 拍照应用的相关代码实现。
1. 在 AndroidManifest.xml 文件中添加相应的权限:
```xml
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
2. 创建 MainActivity 和 CameraActivity 两个 Activity,并在 MainActivity 中添加一个按钮,用于触发跳转到 CameraActivity 的操作。
MainActivity.java
```java
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CODE_CAMERA = 1;
private RecyclerView mRecyclerView;
private PhotoListAdapter mAdapter;
private List<PhotoItem> mPhotoList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mPhotoList = new ArrayList<>();
mAdapter = new PhotoListAdapter(this, mPhotoList);
mRecyclerView.setAdapter(mAdapter);
Button btnCamera = findViewById(R.id.btn_camera);
btnCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, CameraActivity.class);
startActivityForResult(intent, REQUEST_CODE_CAMERA);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_CAMERA && resultCode == RESULT_OK) {
String filePath = data.getStringExtra(CameraActivity.EXTRA_FILE_PATH);
long timeTaken = data.getLongExtra(CameraActivity.EXTRA_TIME_TAKEN, 0);
mPhotoList.add(new PhotoItem(filePath, timeTaken));
mAdapter.notifyDataSetChanged();
}
}
}
```
activity_main.xml
```xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btn_camera"
android:text="拍照"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
```
3. 在 CameraActivity 中添加 SurfaceView 和按钮,并实现相应的 Camera 操作。
CameraActivity.java
```java
public class CameraActivity extends AppCompatActivity implements SurfaceHolder.Callback, Camera.PictureCallback {
public static final String EXTRA_FILE_PATH = "file_path";
public static final String EXTRA_TIME_TAKEN = "time_taken";
private SurfaceView mSurfaceView;
private Camera mCamera;
private File mFile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
mSurfaceView = findViewById(R.id.surface_view);
mSurfaceView.getHolder().addCallback(this);
Button btnTakePicture = findViewById(R.id.btn_take_picture);
btnTakePicture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mCamera.takePicture(null, null, CameraActivity.this);
}
});
Button btnCancel = findViewById(R.id.btn_cancel);
btnCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
}
@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
mCamera = Camera.open();
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
if (mCamera != null) {
mCamera.stopPreview();
try {
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
@Override
public void onPictureTaken(byte[] bytes, Camera camera) {
mFile = getOutputMediaFile();
if (mFile == null) {
Toast.makeText(this, "Failed to create file.", Toast.LENGTH_SHORT).show();
return;
}
try {
FileOutputStream fos = new FileOutputStream(mFile);
fos.write(bytes);
fos.close();
Intent intent = new Intent();
intent.putExtra(EXTRA_FILE_PATH, mFile.getAbsolutePath());
intent.putExtra(EXTRA_TIME_TAKEN, System.currentTimeMillis());
setResult(RESULT_OK, intent);
mSurfaceView.setVisibility(View.GONE);
findViewById(R.id.btn_take_picture).setVisibility(View.GONE);
findViewById(R.id.btn_cancel).setVisibility(View.GONE);
findViewById(R.id.iv_photo).setVisibility(View.VISIBLE);
((ImageView) findViewById(R.id.iv_photo)).setImageBitmap(BitmapFactory.decodeFile(mFile.getAbsolutePath()));
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
finish();
}
}, 3000);
} catch (IOException e) {
e.printStackTrace();
}
}
private File getOutputMediaFile() {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
return new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
}
}
```
activity_camera.xml
```xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<SurfaceView
android:id="@+id/surface_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<RelativeLayout
android:id="@+id/layout_buttons"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal">
<Button
android:id="@+id/btn_take_picture"
android:text="拍照"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
<Button
android:id="@+id/btn_cancel"
android:text="取消"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
</RelativeLayout>
<ImageView
android:id="@+id/iv_photo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone" />
</RelativeLayout>
```
4. 创建 PhotoListAdapter 和 PhotoItem 两个类,用于显示图片列表。
PhotoListAdapter.java
```java
public class PhotoListAdapter extends RecyclerView.Adapter<PhotoListAdapter.ViewHolder> {
private Context mContext;
private List<PhotoItem> mPhotoList;
public PhotoListAdapter(Context context, List<PhotoItem> photoList) {
mContext = context;
mPhotoList = photoList;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item_photo, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
PhotoItem item = mPhotoList.get(position);
holder.ivPhoto.setImageBitmap(BitmapFactory.decodeFile(item.getFilePath()));
holder.tvTime.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(item.getTimeTaken())));
}
@Override
public int getItemCount() {
return mPhotoList.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
ImageView ivPhoto;
TextView tvTime;
ViewHolder(View itemView) {
super(itemView);
ivPhoto = itemView.findViewById(R.id.iv_photo);
tvTime = itemView.findViewById(R.id.tv_time);
}
}
}
```
item_photo.xml
```xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="80dp">
<ImageView
android:id="@+id/iv_photo"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_margin="10dp" />
<TextView
android:id="@+id/tv_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@id/iv_photo"
android:layout_alignParentRight="true"
android:text="2022-01-01 12:00:00"
android:textSize="12sp" />
</RelativeLayout>
```
PhotoItem.java
```java
public class PhotoItem {
private String mFilePath;
private long mTimeTaken;
public PhotoItem(String filePath, long timeTaken) {
mFilePath = filePath;
mTimeTaken = timeTaken;
}
public String getFilePath() {
return mFilePath;
}
public long getTimeTaken() {
return mTimeTaken;
}
}
```
以上就是一个简单的 Camera 拍照应用的代码实现。需要注意的是,该应用使用了 Camera API,而 Camera API 在 Android 5.0 之后被废弃,建议使用 Camera2 API 替代。同时,还需要注意内存泄漏、适配不同分辨率设备等问题。
阅读全文