要打开Android设备的前置摄像头而不是后置摄像头,可以使用Android的Camera2 API。以下是一个使用Camera2 API打开前置摄像头的示例代码:
CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
String cameraId = null;
try {
for (String id : cameraManager.getCameraIdList()) {
CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(id);
Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) {
cameraId = id;
break;
}
}
} catch (CameraAccessException e) {
e.printStackTrace();
}
if (cameraId != null) {
try {
cameraManager.openCamera(cameraId, new CameraDevice.StateCallback() {
@Override
public void onOpened(@NonNull CameraDevice camera) {
// 相机已打开,可以进行后续操作
}
@Override
public void onDisconnected(@NonNull CameraDevice camera) {
// 相机连接断开
}
@Override
public void onError(@NonNull CameraDevice camera, int error) {
// 打开相机发生错误
}
}, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
这样,就可以通过Camera2 API打开Android设备的前置摄像头了。