本篇介绍
回顾下Camera1,使用起来需要开发关注很多细节,Camera2可以帮助开发自动处理很多细节,可是使用上就特别复杂,Android就提供了Camerax,既简单又好用,本篇介绍下使用方法。
使用步骤
- 申请权限
<uses-permission android:name="android.permission.CAMERA" />
动态申请:
代码语言:javascript复制 private void requestPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
return;
}
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, CAMERA_REQUEST_CODE);
}
- 打开Camera:
mCameraProviderFuture = ProcessCameraProvider.getInstance(this);
mCameraProviderFuture.addListener(new Runnable() {
@Override
public void run() {
try {
ProcessCameraProvider cameraProvider = mCameraProviderFuture.get();
Preview preview = new Preview.Builder().build();
ImageAnalysis imageAnalysis =
new ImageAnalysis.Builder().setTargetResolution(new Size(1280, 720)).build();
CameraSelector cameraSelector = CameraSelector.Builder.fromSelector(CameraSelector.DEFAULT_FRONT_CAMERA).build();
cameraProvider.unbind();
cameraProvider.bindToLifecycle(MainActivity.this, cameraSelector, imageAnalysis, preview);
preview.setSurfaceProvider(mPreview.getSurfaceProvider());
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, ContextCompat.getMainExecutor(this));
这就是打开Camera,并且将采集数据渲染出来的全部代码了,很简单。
- 关闭Camera:
try {
mCameraProviderFuture.get().shutdown();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
工程代码路径