Android 7.0 手电筒控制实现
人气:0在AndroidN(7.0)前你对手电筒的控制也许是这样的:
Camera camera = Camera.open(); if(open){ Parameters mParameters = camera.getParameters(); mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); camera.setParameters(mParameters); } else { Parameters mParameters = camera.getParameters(); mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); camera.setParameters(mParameters); } camera.release();
但在Android N(7.0)及以后,也许你就发现不灵了,那你就需要这样做了:
在Android(M)6.0 后,Android引入了新的API,对闪光灯的控制通过CameraManager处理;首先简单的对两个类进行说明:
(1)CameraManager.java:
可通过CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);获得,通过此类与相机设备进行通信。
(2)CameraCharacteristics.java:
给定指定的相机设备ID,通过此类查询相关硬件信息。
手电筒操作
try { //获取CameraManager CameraManager mCameraManager = (CameraManager) MyApplication.getContext().getSystemService(Context.CAMERA_SERVICE); //获取当前手机所有摄像头设备ID String[] ids = mCameraManager.getCameraIdList(); for (String id : ids) { CameraCharacteristics c = mCameraManager.getCameraCharacteristics(id); //查询该摄像头组件是否包含闪光灯 Boolean flashAvailable = c.get(CameraCharacteristics.FLASH_INFO_AVAILABLE); /* * 获取相机面对的方向 * CameraCharacteristics.LENS_FACING_FRONT 前置摄像头 * CameraCharacteristics.LENS_FACING_BACK 后只摄像头 * CameraCharacteristics.LENS_FACING_EXTERNAL 外部的摄像头 */ Integer lensFacing = c.get(CameraCharacteristics.LENS_FACING); if (flashAvailable != null && flashAvailable && lensFacing != null && lensFacing == CameraCharacteristics.LENS_FACING_BACK) { //打开或关闭手电筒 mCameraManager.setTorchMode(id, OPEN? true:false); } } } catch (CameraAccessException e) { e.printStackTrace(); }
您可能感兴趣的文章:
加载全部内容