在AndroidManifest.xml文件中,添加相机权限声明:
同时,在代码中添加检查相机是否可用的逻辑: // Check if device has camera private boolean checkCameraHardware(Context context) { if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){ // this device has a camera return true; } else { // no camera on this device return false; } }
// Check if camera is available private boolean isCameraAvailable() { Camera camera = null; try { camera = Camera.open(); } catch (Exception e) { e.printStackTrace(); } return (camera != null); }
// Use the camera private void useCamera() { // Check if the device has a camera if (!checkCameraHardware(this)) { Toast.makeText(this, "This device does not have a camera.", Toast.LENGTH_SHORT).show(); return; }
// Check if the camera is available
if (!isCameraAvailable()) {
Toast.makeText(this, "The camera is not available.", Toast.LENGTH_SHORT).show();
return;
}
// Open the camera
Camera camera = null;
try {
camera = Camera.open();
} catch (Exception e) {
e.printStackTrace();
}
if (camera != null) {
// Use the camera
// ...
// Release the camera
camera.release();
}
}