Android Camera2设置预览示例代码
时间: 2023-09-09 14:05:50 浏览: 134
当然,这里是一个简单的 Android Camera2 设置预览的示例代码:
首先,你需要在你的 AndroidManifest.xml 文件中添加相机权限:
```xml
<uses-permission android:name="android.permission.CAMERA" />
```
然后,在你的活动或片段类中,你需要声明一些成员变量:
```java
private CameraManager cameraManager;
private String cameraId;
private CameraDevice cameraDevice;
private CameraCaptureSession cameraCaptureSession;
private CaptureRequest.Builder captureRequestBuilder;
private ImageReader imageReader;
private SurfaceView surfaceView;
```
接下来,在你的 onCreate 方法中初始化这些变量:
```java
surfaceView = findViewById(R.id.surfaceView);
cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
cameraId = cameraManager.getCameraIdList()[0];
} catch (CameraAccessException e) {
e.printStackTrace();
}
```
然后,在 onResume 方法中打开相机并设置预览:
```java
@Override
protected void onResume() {
super.onResume();
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
openCamera();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// 不需要实现
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// 不需要实现
}
});
}
```
在 openCamera 方法中打开相机,并设置预览会话:
```java
private void openCamera() {
try {
cameraManager.openCamera(cameraId, new CameraDevice.StateCallback() {
@Override
public void onOpened(@NonNull CameraDevice camera) {
cameraDevice = camera;
createCameraPreviewSession();
}
@Override
public void onDisconnected(@NonNull CameraDevice camera) {
cameraDevice.close();
cameraDevice = null;
}
@Override
public void onError(@NonNull CameraDevice camera, int error) {
cameraDevice.close();
cameraDevice = null;
}
}, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
```
在 createCameraPreviewSession 方法中创建预览会话,并设置预览请求:
```java
private void createCameraPreviewSession() {
try {
Surface surface = surfaceView.getHolder().getSurface();
captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
captureRequestBuilder.addTarget(surface);
cameraDevice.createCaptureSession(Arrays.asList(surface, imageReader.getSurface()), new CameraCaptureSession.StateCallback() {
@Override
public void onConfigured(@NonNull CameraCaptureSession session) {
cameraCaptureSession = session;
try {
cameraCaptureSession.setRepeatingRequest(captureRequestBuilder.build(), null, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@Override
public void onConfigureFailed(@NonNull CameraCaptureSession session) {
// 处理配置失败的情况
}
}, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
```
最后,在 onPause 方法中释放相机资源:
```java
@Override
protected void onPause() {
super.onPause();
if (cameraCaptureSession != null) {
cameraCaptureSession.close();
cameraCaptureSession = null;
}
if (cameraDevice != null) {
cameraDevice.close();
cameraDevice = null;
}
}
```
以上就是一个简单的 Android Camera2 设置预览的示例代码。希望对你有所帮助!如果还有其他问题,请随时提问。
阅读全文