Java:

/*
*作者:赵星海
*时间:2021/3/23 15:44
*用途:是否有可用摄像头
*/
public static boolean isCamera() {
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;
//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;
}

kotlin:

/*
*作者:赵星海
*时间:2021/3/23 15:44
*用途:是否有可用摄像头
*/
fun isCamera(): Boolean {
var result: Boolean
var camera: Camera? = null
try {
camera = Camera.open()
if (camera == null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
var connected = false
for (camIdx in 0 until Camera.getNumberOfCameras()) {
Log.d("TAG", "Trying to open camera with new open(" + Integer.valueOf(camIdx) + ")")
try {
camera = Camera.open(camIdx)
connected = true
} catch (e: RuntimeException) {
Log.e("TAG", "Camera #" + camIdx + "failed to open: " + e.localizedMessage)
}
if (connected) {
break
}
}
}
val supportedPreviewSizes: List<Camera.Size> = camera?.getParameters()?.getSupportedPreviewSizes() as List<Camera.Size>
result = supportedPreviewSizes != null
//start the preview
Log.d("TAG", "startPreview")
camera?.startPreview()
} catch (e: java.lang.Exception) {
Log.e("TAG", "Camera is not available (in use or does not exist): " + e.localizedMessage)
result = false
} finally {
if (camera != null) {
camera.release()
}
}
return result
}