如何检测 android 中前置摄像头是否可用?
How to detect if front camera is available in android?
实际上我的应用程序有一些问题,
就像我有一个按钮可以打开前置摄像头并扫描服务员徽章,但是当我尝试检查设备是否有摄像头并且如果没有我只是隐藏那个按钮时,问题就来了。
但是我有一个设备使用前置摄像头作为 QR 扫描仪,所以它不是真正可以使用的摄像头,所以当我尝试单击该按钮时应用程序崩溃。
所以问题是我如何处理和检查相机是否不仅存在,而且是否有效?
使用此方法检测设备是否有前置摄像头。
private boolean hasFrontCamera() {
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
Camera.getCameraInfo(i, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
return true;
}
}
return false;
}
Android Pie 添加更多features 用于枚举相机:
Apps running on Android 9 devices can discover every available camera by calling getCameraIdList(). An app should not assume that the device has only a single back camera or only a single front camera.
For example, if your app has a button to switch between the front and back cameras, there may be more than one front or back camera to choose from. You should walk the camera list, examine each camera's characteristics, and decide which cameras to expose to the user.
您可以使用 PackageManager hasSystemFeature() 函数检查设备中是否有前置摄像头
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT)){
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
实际上我的应用程序有一些问题,
就像我有一个按钮可以打开前置摄像头并扫描服务员徽章,但是当我尝试检查设备是否有摄像头并且如果没有我只是隐藏那个按钮时,问题就来了。
但是我有一个设备使用前置摄像头作为 QR 扫描仪,所以它不是真正可以使用的摄像头,所以当我尝试单击该按钮时应用程序崩溃。
所以问题是我如何处理和检查相机是否不仅存在,而且是否有效?
使用此方法检测设备是否有前置摄像头。
private boolean hasFrontCamera() {
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
Camera.getCameraInfo(i, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
return true;
}
}
return false;
}
Android Pie 添加更多features 用于枚举相机:
Apps running on Android 9 devices can discover every available camera by calling getCameraIdList(). An app should not assume that the device has only a single back camera or only a single front camera.
For example, if your app has a button to switch between the front and back cameras, there may be more than one front or back camera to choose from. You should walk the camera list, examine each camera's characteristics, and decide which cameras to expose to the user.
您可以使用 PackageManager hasSystemFeature() 函数检查设备中是否有前置摄像头
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT)){
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}