Android开启闪光灯的方法 Android打开手电筒功能

时间:2019-03-30
本文章向大家介绍Android开启闪光灯的方法 Android打开手电筒功能,主要包括Android开启闪光灯的方法 Android打开手电筒功能使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

前言

众所周知,安卓的手电筒功能无非是开启手机的闪光灯,既然开启闪光灯就必须要与相机关联。

代码

写了个小工具,一个文件搞定。

public class FlashUtils {

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

  //使用单例模式在这里初始化相机
  public static FlashUtils getInstance() {
    if (utils == null) {
      utils = new FlashUtils();
    }
    try {
      if (camera == null) {
        camera = Camera.open();
      }
    } catch (Exception e) {
      if (camera != null) {
        camera.release();
      }
      camera = null;
    }
    return utils;
  }

  //参考二维码工具的闪光灯
  public void switchFlash() {
    try {
      Parameters parameters = camera.getParameters();
      if (mIsOpen) {
        if (parameters.getFlashMode().equals("torch")) {
          return;
        } else {
          parameters.setFlashMode("torch");
        }
      } else {
        if (parameters.getFlashMode().equals("off")) {
          return;
        } else {
          parameters.setFlashMode("off");
        }
      }
      camera.setParameters(parameters);
    } catch (Exception e) {
      finishFlashUtils();
    }
    mIsOpen = !mIsOpen;
  }

  //页面销毁的时候调用此方法
  public void finishFlashUtils() {
    if (camera != null) {
      camera.stopPreview();
      camera.release();
    }
    camera = null;
  }

} 

6.0及其以上亲测可用,需手动打开权限。

5.0以下暂未测试。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。