做一个考勤机的功能,需要检测系统摄像头是否可以使用,避免闪退,自己写了一个方法。
public static boolean checkCameraEnable() {
boolean result;
Camera camera = null;
try {
camera = Camera.open();
if (camera == null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
boolean connected = false;
for (int camIdx = 0; camIdx < Camera.getNumberOfCameras(); ++camIdx) {
Log.d("came", "Trying to open camera with new open(" + Integer.valueOf(camIdx) + ")");
try {
camera = Camera.open(camIdx);
connected = true;
} catch (RuntimeException e) {
Log.e("came", "Camera #" + camIdx + "failed to open: " + e.getLocalizedMessage());
}
if (connected) {
break;
}
}
}
List<Camera.Size> supportedPreviewSizes = camera.getParameters().getSupportedPreviewSizes();
result = supportedPreviewSizes != null;
/* Finally we are ready to start the preview */
Log.d("came", "startPreview");
camera.startPreview();
} catch (Exception e) {
Log.e("came", "Camera is not available (in use or does not exist): " + e.getLocalizedMessage());
result = false;
} finally {
if (camera != null) {
camera.release();
}
}
return result;
}
拿走不谢!