SoFunction
Updated on 2025-04-10

Android 7.0 flashlight control implementation

Before AndroidN (7.0) your control on flashlight might look like this:

Camera camera = ();
if(open){ 
  Parameters mParameters = (); 
  (.FLASH_MODE_TORCH); 
  (mParameters);  
} else { 
  Parameters mParameters = (); 
  (.FLASH_MODE_OFF); 
  (mParameters); 
} 
();

But in Android N (7.0) and later, maybe you find that it doesn't work, so you need to do this:

After Android (M) 6.0, Android introduced a new API, and the control of flash is handled through CameraManager; first, we briefly explain the two classes:

(1):

It can be obtained through CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE); to communicate with the camera device through this type.

(2):

Given the specified camera device ID, query the relevant hardware information through this type.

Flashlight operation

try {
  //Get CameraManager  CameraManager mCameraManager = (CameraManager) ().getSystemService(Context.CAMERA_SERVICE);
  //Get all camera device IDs of the current mobile phone  String[] ids = ();
  for (String id : ids) {
    CameraCharacteristics c = (id);
    //Check whether the camera component contains a flash    Boolean flashAvailable = (CameraCharacteristics.FLASH_INFO_AVAILABLE);
    /*
     * Get the direction the camera faces
     * CameraCharacteristics.LENS_FACING_FRONT Front camera
     * CameraCharacteristics.LENS_FACING_BACK only cameras
     * CameraCharacteristics.LENS_FACING_EXTERNAL External camera
     */
    Integer lensFacing = (CameraCharacteristics.LENS_FACING);
    if (flashAvailable != null && flashAvailable
        && lensFacing != null && lensFacing == CameraCharacteristics.LENS_FACING_BACK) {
      //Open or close the flashlight      (id, OPEN? true:false);
    }
  }

} catch (CameraAccessException e) {
  ();
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.