操作闪光灯(手电筒)
private CameraManager mCameraManager;private boolean mTorchAvailable;private String mCameraId;private boolean mFlashlightEnabled;// 判断是否支持public boolean hasFlashlight() {return mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);}mCameraManager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE);try {mCameraId = getCameraId();} catch (Throwable e) {Log.e(TAG, "Couldn't initialize.", e);return;}// 注册针对闪光灯的状态回调if (mCameraId != null) {mCameraManager.registerTorchCallback(mTorchCallback, null);}private String getCameraId() throws CameraAccessException { String[] ids = mCameraManager.getCameraIdList();for (String id : ids) {CameraCharacteristics c = mCameraManager.getCameraCharacteristics(id);Boolean flashAvailable = c.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);Integer lensFacing = c.get(CameraCharacteristics.LENS_FACING);if (flashAvailable != null && flashAvailable&& lensFacing != null && lensFacing == CameraCharacteristics.LENS_FACING_BACK) {return id;}}return null;}// 状态回调private final CameraManager.TorchCallback mTorchCallback =new CameraManager.TorchCallback() {@Overridepublic void onTorchModeUnavailable(String cameraId) {if (TextUtils.equals(cameraId, mCameraId)) {setCameraAvailable(false);}}@Overridepublic void onTorchModeChanged(String cameraId, boolean enabled) {if (TextUtils.equals(cameraId, mCameraId)) {setCameraAvailable(true); mFlashlightEnabled = enabled; }}private void setCameraAvailable(boolean available) {mTorchAvailable = available;}}; // 开启/关闭闪光灯public void setFlashlight(boolean enabled) {synchronized (this) {if (mCameraId == null || !mTorchAvailable){return; } if (mFlashlightEnabled != enabled) {mFlashlightEnabled = enabled;try {mCameraManager.setTorchMode(mCameraId, enabled);} catch (CameraAccessException e) {Log.e(TAG, "Couldn't set torch mode", e); } }}}