下面列出了怎么用android.hardware.camera2.CameraManager的API类实例代码及写法,或者点击链接到github查看源代码。
private static boolean isMonochrome(@NonNull String deviceName, @NonNull CameraManager cameraManager) {
try {
CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(deviceName);
int[] capabilities = characteristics.get(CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES);
if (capabilities != null) {
for (int capability : capabilities) {
if (capability == CameraMetadata.REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME) {
return true;
}
}
}
} catch (CameraAccessException e) {
return false;
}
return false;
}
@RequiresApi(21)
public static int getLowestSupportedHardwareLevel(@NonNull Context context) {
@SuppressLint("RestrictedApi") CameraManager cameraManager = CameraManagerCompat.from(context).unwrap();
try {
int supported = maxHardwareLevel();
for (String cameraId : cameraManager.getCameraIdList()) {
CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId);
Integer hwLevel = characteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL);
if (hwLevel == null || hwLevel == CameraMetadata.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY) {
return CameraMetadata.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY;
}
supported = smallerHardwareLevel(supported, hwLevel);
}
return supported;
} catch (CameraAccessException e) {
Log.w(TAG, "Failed to enumerate cameras", e);
return CameraMetadata.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY;
}
}
public void forceScanAllCameras(Activity activity) {
CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
try {
String[] idList = manager.getCameraIdList();
int maxCameraCnt = idList.length;
for (int index = 0; index < maxCameraCnt; index++) {
String cameraId = manager.getCameraIdList()[index];
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
}
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@TargetApi(21)
public static Size[] querySupportResolution(Context context, int index) {
CameraManager manager =
(CameraManager)context.getSystemService(CAMERA_SERVICE);
try {
CameraCharacteristics chars
= manager.getCameraCharacteristics(index+"");
StreamConfigurationMap configurationMap = chars.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
return configurationMap.getOutputSizes(ImageFormat.YUV_420_888);
} catch(CameraAccessException e){
e.printStackTrace();
}
return null;
}
/**
* カメラID に対応したカメラデバイスがサポートしているプレビューサイズのリストを取得します.
*
* @param cameraManager カメラマネージャ
* @param cameraId カメラID
* @return サポートしているプレビューサイズのリスト
*/
@NonNull
static List<Size> getSupportedPreviewSizes(final CameraManager cameraManager, final String cameraId) {
List<Size> previewSizes = new ArrayList<>();
try {
CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId);
StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
if (map != null) {
previewSizes = Arrays.asList(map.getOutputSizes(SurfaceTexture.class));
Collections.sort(previewSizes, SizeComparator);
}
} catch (CameraAccessException e) {
// ignore.
}
return previewSizes;
}
public boolean isCamera2Native() {
try {
if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return false;
}
manager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE);
mCameraId = manager.getCameraIdList()[mFacing];
CameraCharacteristics characteristics = manager.getCameraCharacteristics(mCameraId);
//CHECK CAMERA HARDWARE LEVEL. IF CAMERA2 IS NOT NATIVELY SUPPORTED, GO BACK TO CAMERA1
Integer deviceLevel = characteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL);
return deviceLevel != null && (deviceLevel != CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY);
} catch (CameraAccessException ex) {
return false;
} catch (NullPointerException e) {
return false;
} catch (ArrayIndexOutOfBoundsException ez) {
return false;
}
}
public CustomVideoCapturerCamera2(Context ctx,
Publisher.CameraCaptureResolution resolution,
Publisher.CameraCaptureFrameRate fps) {
cameraManager = (CameraManager) ctx.getSystemService(Context.CAMERA_SERVICE);
display = ((WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
camera = null;
cameraState = CameraState.CLOSED;
reentrantLock = new ReentrantLock();
condition = reentrantLock.newCondition();
frameDimensions = resolutionTable.get(resolution.ordinal());
desiredFps = frameRateTable.get(fps.ordinal());
runtimeExceptionList = new ArrayList<RuntimeException>();
isPaused = false;
try {
String camId = selectCamera(PREFERRED_FACING_CAMERA);
/* if default camera facing direction is not found, use first camera */
if (null == camId && (0 < cameraManager.getCameraIdList().length)) {
camId = cameraManager.getCameraIdList()[0];
}
cameraIndex = findCameraIndex(camId);
} catch (CameraAccessException e) {
throw new Camera2Exception(e.getMessage());
}
}
AndroidCamera2AgentImpl(Context context) {
mCameraHandlerThread = new HandlerThread("Camera2 Handler Thread");
mCameraHandlerThread.start();
mCameraHandler = new Camera2Handler(mCameraHandlerThread.getLooper());
mExceptionHandler = new CameraExceptionHandler(mCameraHandler);
mCameraState = new AndroidCamera2StateHolder();
mDispatchThread = new DispatchThread(mCameraHandler, mCameraHandlerThread);
mDispatchThread.start();
mCameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
mNoisemaker = new MediaActionSound();
mNoisemaker.load(MediaActionSound.SHUTTER_CLICK);
mNumCameraDevices = 0;
mCameraDevices = new ArrayList<String>();
updateCameraDevices();
}
public CameraDevice captureCameraDevice() throws Exception {
CameraManager manager =
(CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE);
String id = manager.getCameraIdList()[0];
synchronized (this) {
manager.openCamera(id, this, sHandler);
wait();
}
return mCamera;
}
/**
* カメラが取り付けられている向きを取得します.
*
* @param context コンテキスト
* @param facing カメラのタイプ
* @return カメラの向き(0, 90, 180, 270)
*/
public static int getSensorOrientation(Context context, int facing) {
CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
if (manager == null) {
throw new UnsupportedOperationException("Not supported a Camera.");
}
try {
String cameraId = Camera2Helper.getCameraId(manager, facing);
if (cameraId != null) {
return Camera2Helper.getSensorOrientation(manager, cameraId);
}
} catch (CameraAccessException e) {
// ignore.
}
throw new UnsupportedOperationException("Not supported a Camera.");
}
private float getMinimumFocusDistance() {
if (mCameraId == null)
return 0;
Float minimumLens = null;
try {
CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
CameraCharacteristics c = manager.getCameraCharacteristics(mCameraId);
minimumLens = c.get(CameraCharacteristics.LENS_INFO_MINIMUM_FOCUS_DISTANCE);
} catch (Exception e) {
Log.e(TAG, "isHardwareLevelSupported Error", e);
}
if (minimumLens != null)
return minimumLens;
return 0;
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private static List<MyCameraInfo> GetAllCameras2(Context context) throws Exception {
List<MyCameraInfo> cameras = new ArrayList<>();
CameraManager cameraManager =
(CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
for (String cameraId : cameraManager.getCameraIdList()) {
CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId);
MyCameraInfo cameraInfo = MyCameraInfo.CreateFromCameraCharacteristics(cameraId,
characteristics);
cameras.add(cameraInfo);
}
return cameras;
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void initCamera() {
try {
CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
String[] cameraIds = cameraManager.getCameraIdList();
if (cameraIds.length == 0) return;
String cameraId = cameraIds[0];
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSIONS_REQUEST);
}
cameraManager.openCamera(cameraId, cameraDeviceCallback, null);
} catch (CameraAccessException e) {
Log.d(TAG, "No access to the camera.", e);
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void initCamera() {
cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
String[] cameraIds = new String[0];
try {
cameraIds = cameraManager.getCameraIdList();
if (cameraIds.length == 0) return;
cameraId = cameraIds[0];
} catch (CameraAccessException e) {
Log.e(TAG, "Camera Error.", e);
return;
}
}
public Size[] getSupportedPictureSizes(String cameraId) {
Size[] outputSizes = null;
CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
try {
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
StreamConfigurationMap map = characteristics.get(
CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
if (map != null) {
outputSizes = map.getOutputSizes(ImageFormat.JPEG);
}
} catch (CameraAccessException e) {
Log.w(TAG, e);
}
return outputSizes;
}
FilteredCamera2Enumerator(@NonNull Context context) {
super(context);
this.context = context;
this.cameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
this.deviceNames = null;
}
@ReactMethod
public void switchState(Boolean newState, Callback successCallback, Callback failureCallback) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
CameraManager cameraManager =
(CameraManager) this.myReactContext.getSystemService(Context.CAMERA_SERVICE);
try {
String cameraId = cameraManager.getCameraIdList()[0];
cameraManager.setTorchMode(cameraId, newState);
successCallback.invoke(true);
} catch (Exception e) {
String errorMessage = e.getMessage();
failureCallback.invoke("Error: " + errorMessage);
}
} else {
Camera.Parameters params;
if (newState && !isTorchOn) {
camera = Camera.open();
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isTorchOn = true;
} else if (isTorchOn) {
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
camera.release();
isTorchOn = false;
}
}
}
protected Camera2(Context c, int id, int width, int height , SurfaceView surfaceView) {
manager = (CameraManager) c.getSystemService(CAMERA_SERVICE);
mContext = c;
startBackgroundThread();
cameraId = id + "";
mWidth = width;
mHeight = height;
mDisplaySurfaceView = surfaceView;
}
protected Camera2(Context c, int id, int width, int height , SurfaceTexture surfaceTexture) {
manager = (CameraManager) c.getSystemService(CAMERA_SERVICE);
mContext = c;
startBackgroundThread();
cameraId = id + "";
mWidth = width;
mHeight = height;
mDisplaySurfaceTexture = surfaceTexture;
}
private String chooseCamera() {
final CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
for (final String cameraId : manager.getCameraIdList()) {
final CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
// We don't use a front facing camera in this sample.
final Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) {
continue;
}
final StreamConfigurationMap map =
characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
if (map == null) {
continue;
}
// Fallback to camera1 API for internal cameras that don't have full support.
// This should help with legacy situations where using the camera2 API causes
// distorted or otherwise broken previews.
useCamera2API = (facing == CameraCharacteristics.LENS_FACING_EXTERNAL)
|| isHardwareLevelSupported(characteristics,
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL);
Log.i(TAG, "Camera API lv2?: " + useCamera2API);
return cameraId;
}
} catch (CameraAccessException e) {
Log.e(TAG, "Not allowed to access camera: " + e);
}
return null;
}
private String chooseCamera() {
final CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
for (final String cameraId : manager.getCameraIdList()) {
final CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
// We don't use a front facing camera in this sample.
final Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) {
continue;
}
final StreamConfigurationMap map =
characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
if (map == null) {
continue;
}
// Fallback to camera1 API for internal cameras that don't have full support.
// This should help with legacy situations where using the camera2 API causes
// distorted or otherwise broken previews.
useCamera2API = (facing == CameraCharacteristics.LENS_FACING_EXTERNAL)
|| isHardwareLevelSupported(characteristics,
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL);
Log.i(TAG, "Camera API lv2?: " + useCamera2API);
return cameraId;
}
} catch (CameraAccessException e) {
Log.e(TAG, "Not allowed to access camera: " + e);
}
return null;
}
@TargetApi(21)
private void doToggleTorchSdk23(boolean switchOn) throws IOException, CameraAccessException {
final CameraManager cameraManager = (CameraManager) cordova.getActivity().getSystemService(Context.CAMERA_SERVICE);
for (final String id : cameraManager.getCameraIdList()) {
// Turn on the flash if the camera has one (usually the one at index 0 has one)
final Boolean hasFlash = cameraManager.getCameraCharacteristics(id).get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
if (Boolean.TRUE.equals(hasFlash)) {
setTorchMode(cameraManager, id, switchOn);
break;
}
}
}
@TargetApi(VERSION_CODES.LOLLIPOP)
PostMarshmallow(Context context) {
cameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
try {
if (cameraManager != null) {
cameraId = cameraManager.getCameraIdList()[0];
}
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@SuppressLint("MissingPermission")
@RequiresPermission(android.Manifest.permission.CAMERA)
private void openCamera(CameraManager cameraManager, CameraConfig config) {
try {
cameraManager.openCamera(config.cameraId, config.cameraStateCallback, handler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@TargetApi(Build.VERSION_CODES.M)
public Camera2Proxy(Activity activity) {
mActivity = activity;
mCameraManager = (CameraManager) mActivity.getSystemService(Context.CAMERA_SERVICE);
mOrientationEventListener = new OrientationEventListener(mActivity) {
@Override
public void onOrientationChanged(int orientation) {
mDeviceOrientation = orientation;
}
};
}
public SubmitInfo submitRequest(CaptureRequest request, boolean streaming)
throws CameraAccessException {
try {
return mRemoteDevice.submitRequest(request, streaming);
} catch (Throwable t) {
CameraManager.throwAsPublicException(t);
throw new UnsupportedOperationException("Unexpected exception", t);
}
}
public SubmitInfo submitRequestList(CaptureRequest[] requestList, boolean streaming)
throws CameraAccessException {
try {
return mRemoteDevice.submitRequestList(requestList, streaming);
} catch (Throwable t) {
CameraManager.throwAsPublicException(t);
throw new UnsupportedOperationException("Unexpected exception", t);
}
}
private static CameraCharacteristics getCameraCharacteristics(int id) {
final CameraManager manager =
(CameraManager) ContextUtils.getApplicationContext().getSystemService(
Context.CAMERA_SERVICE);
try {
return manager.getCameraCharacteristics(Integer.toString(id));
} catch (CameraAccessException ex) {
Log.e(TAG, "getCameraCharacteristics: ", ex);
}
return null;
}
/**
* Initialize the camera device
*/
@SuppressLint("MissingPermission")
public void initializeCamera(Context context, int previewWidth, int previewHeight,
Handler backgroundHandler,
ImageReader.OnImageAvailableListener imageAvailableListener) {
if (initialized) {
throw new IllegalStateException(
"CameraHandler is already initialized or is initializing");
}
initialized = true;
// Discover the camera instance
CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
String[] camIds = null;
try {
camIds = manager.getCameraIdList();
} catch (CameraAccessException e) {
Log.w(TAG, "Cannot get the list of available cameras", e);
}
if (camIds == null || camIds.length < 1) {
Log.d(TAG, "No cameras found");
return;
}
Log.d(TAG, "Using camera id " + camIds[0]);
// Initialize the image processor
mImageReader = ImageReader.newInstance(previewWidth, previewHeight, ImageFormat.JPEG,
MAX_IMAGES);
mImageReader.setOnImageAvailableListener(imageAvailableListener, backgroundHandler);
// Open the camera resource
try {
manager.openCamera(camIds[0], mStateCallback, backgroundHandler);
} catch (CameraAccessException cae) {
Log.d(TAG, "Camera access exception", cae);
}
}
public void deleteStream(int streamId) throws CameraAccessException {
try {
mRemoteDevice.deleteStream(streamId);
} catch (Throwable t) {
CameraManager.throwAsPublicException(t);
throw new UnsupportedOperationException("Unexpected exception", t);
}
}