在AndroidManifest.xml文件中添加以下代码:
如果应用程序需要访问前后置摄像头,请添加以下代码:
private boolean isVideoCaptureSupported(Context context) {
PackageManager packageManager = context.getPackageManager();
if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA) || packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT)) {
return true;
} else {
return false;
}
}
使用Camera.open()方法打开摄像头之前,您应该检查是否有另一个应用正在使用摄像头。您可以使用以下代码检查摄像头是否可用:
private boolean isCameraAvailable(Camera camera) {
return camera != null;
}
每个Android设备的摄像头配置不同,因此在配置摄像头之前,您应该先从设备获取可用的摄像头。使用以下代码获取摄像头ID:
private int getCameraId() {
int cameraId = -1;
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
cameraId = i;
break;
}
}
return cameraId;
}
根据相机ID打开相机:
try {
camera = Camera.open(cameraId);
} catch (Exception e) {
Log.e(TAG, "failed to open Camera");
}