How to realize flashlight control by Android7.0
Xiaobian to share with you how Android 7.0 to achieve flashlight control, I believe most people still do not know how to share this article for your reference, I hope you have a lot of harvest after reading this article, let's go to understand it together!
Before Android N (7.0), your control of the flashlight might look like this:
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();
But in Android N (7.0) and later, you may find that it does not work, then you need to do this:
After Android (M) 6.0, Android introduced a new API, the control of the flash is handled through CameraManager; first, two classes are simply explained:
(1)CameraManager.java:
Available through CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);, this class communicates with camera devices.
(2)CameraCharacteristics.java:
Given a specified camera device ID, query related hardware information through this class.
Flashlight operation
try { //Get CameraManager CameraManager mCameraManager =(CameraManager) MyApplication.getContext().getSystemService (Context.CAMERA_SERVICE); //Get all camera IDs of the current phone String[] ids = mCameraManager.getCameraIdList(); for (String id : ids) { CameraCharacteristics c = mCameraManager.getCameraCharacteristics(id);//Query whether the camera component contains flash Boolean flashAvailable = c.get (CameraCharacteristics.FLASH_INFO_AVAILABLE);/* * Get the direction the camera is facing * CameraCharacteristics.LENS_FACING_FRONT camera * CameraCharacteristics.LENS_FACING_BACK camera * CameraCharacteristics.LENS_FACING_BACK EXTERNAL External camera */ Integer lensFacing = c.get(CameraCharacteristics.LENS_FACING); if (flashAvailable != null && flashAvailable && lensFacing != null && lensFacing == CameraCharacteristics.LENS_FACING_BACK) { //Turn the flashlight on or off mCameraManager.setTorchMode(id, OPEN? true:false); } }} catch (CameraAccessException e) { e.printStackTrace();}
The above is "Android 7.0 how to achieve flashlight control" all the content of this article, thank you for reading! I believe that everyone has a certain understanding, hope to share the content to help everyone, if you still want to learn more knowledge, welcome to pay attention to the industry information channel!