最近在做个刷脸支付功能,需求是当打开刷脸支付功能之前检查一下是否具有摄像头且为可用才允许开启。在网上找了实现方法,都不十分靠谱。以下是我的实现代码,供大家参考一下,有更好方案请提出。
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(TAG, "Trying to open camera with new open(" + Integer.valueOf(camIdx) + ")");
try {
camera = Camera.open(camIdx);
connected = true;
} catch (RuntimeException e) {
Log.e(TAG, "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(TAG, "startPreview");
camera.startPreview();
} catch (Exception e) {
Log.e(TAG, "Camera is not available (in use or does not exist): " + e.getLocalizedMessage());
result = false;
} finally {
if (camera != null) {
camera.release();
}
}
return result;
}