SoFunction
Updated on 2025-04-10

How to turn on the flashlight on Android Android Turn on the flashlight function

Preface

As we all know, Android's flashlight function is nothing more than turning on the flash of the phone. Since the flash is turned on, it must be associated with the camera.

Code

I wrote a gadget and got it done with one file.

public class FlashUtils {

  private static FlashUtils utils;
  private static Camera camera;
  public static boolean mIsOpen = true;

  //Initialize the camera here using singleton mode  public static FlashUtils getInstance() {
    if (utils == null) {
      utils = new FlashUtils();
    }
    try {
      if (camera == null) {
        camera = ();
      }
    } catch (Exception e) {
      if (camera != null) {
        ();
      }
      camera = null;
    }
    return utils;
  }

  //Refer to the flash of the QR code tool  public void switchFlash() {
    try {
      Parameters parameters = ();
      if (mIsOpen) {
        if (().equals("torch")) {
          return;
        } else {
          ("torch");
        }
      } else {
        if (().equals("off")) {
          return;
        } else {
          ("off");
        }
      }
      (parameters);
    } catch (Exception e) {
      finishFlashUtils();
    }
    mIsOpen = !mIsOpen;
  }

  //Call this method when the page is destroyed  public void finishFlashUtils() {
    if (camera != null) {
      ();
      ();
    }
    camera = null;
  }

} 

6.0 and above are available in personal tests, and permissions need to be opened manually.

Not tested below 5.0.

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.