通过AndroidView获取CameraPreview的步骤如下:
<uses-permission android:name="android.permission.CAMERA" />
<SurfaceView
android:id="@+id/surfaceView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
private SurfaceView surfaceView;
private Camera camera;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
surfaceView = findViewById(R.id.surfaceView);
}
@Override
protected void onResume() {
super.onResume();
openCamera();
startPreview();
}
@Override
protected void onPause() {
super.onPause();
stopPreview();
releaseCamera();
}
private void openCamera() {
camera = Camera.open();
}
private void startPreview() {
try {
camera.setPreviewDisplay(surfaceView.getHolder());
camera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
private void stopPreview() {
camera.stopPreview();
}
private void releaseCamera() {
camera.release();
camera = null;
}
private static final int REQUEST_CAMERA_PERMISSION = 200;
private void requestCameraPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA_PERMISSION);
} else {
// 已经有相机权限,执行相机相关操作
openCamera();
startPreview();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode == REQUEST_CAMERA_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// 用户授予了相机权限,执行相机相关操作
openCamera();
startPreview();
} else {
// 用户拒绝了相机权限,可以给出相应提示
}
}
}
通过以上步骤,你可以通过AndroidView获取CameraPreview,并在SurfaceView上显示相机预览。请注意,这只是获取相机预览的基本步骤,你可以根据具体需求进行更多的相机操作和功能扩展。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云