android 闪光灯(手电筒)工具类

这是kotlin代码,复制代码的时候,请不要复制到java文件 ╮(╯▽╰)╭

java源码在下面!!

android11逻辑没变,所以放到android11依旧兼容

需要闪光灯权限:
<uses-permission android:name="android.permission.FLASHLIGHT"/>
部分手机(以api21-23手机为主)需要摄像头权限:(敏感权限)
<uses-permission android:name="android.permission.CAMERA"/>

调用前,至少需要初始化一次,可以考虑在Application里调用(此处不需要权限)
FlashlightUtils.init(context)

开启闪光灯:
FlashlightUtils.linghtOn()

关闭闪光灯:
FlashlightUtils.linghtOff()

开启sos 
FlashlightUtils.sos()

关闭sos
FlashlightUtils.offSos()

判断有没有闪光灯设备
FlashlightUtils.hasFlashlight()

判断闪光灯是否打开
FlashlightUtils.isOpen()




import android.content.Context
import android.content.pm.PackageManager
import android.hardware.Camera
import android.hardware.camera2.CameraManager
import android.os.Build
import android.os.CountDownTimer
import android.widget.Toast
import androidx.annotation.IntRange
import androidx.annotation.RequiresApi

/**
 * Created by jingzz on 2020/4/27.
 */
object FlashlightUtils {
    private lateinit var context: Context

    @JvmField
    var isOn = false
    private var timer: Timer? = null

    @JvmStatic
    fun init(context: Context) {
        this.context = context.applicationContext
    }

    /**
     * 开启闪光灯
     */
    @JvmStatic
    fun linghtOn() = linghtOn(false)

    /**
     * 关闭闪光灯
     */
    @JvmStatic
    fun linghtOff() = linghtOff(false)

    /**
     * 开启sos,speed越大速度越快,建议取值 1-6
     */
    @JvmStatic
    fun sos(@IntRange(from = 1, to = 6) speed: Int) {
        //先关闭闪光灯
        linghtOff()
        timer?.cancel()
        val countDownInterval = (1500 / speed).toLong()
        timer = Timer(countDownInterval) {
            if (isOn) linghtOff(true) else linghtOn(true)
        }
        timer?.start()

    }

    /**
     * 关闭闪光灯
     */
    @JvmStatic
    fun offSos(){
        timer?.cancel()
        linghtOff(true)
    }


    private val linghtOn = { isSos: Boolean ->
        if (!isSos)
            timer?.cancel()

        if (hasFlashlight()) {
            isOn = true
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
                linghtOn22()
            else
                linghtOn23()
        } else
            Toast.makeText(context, "该设备没有闪光灯", Toast.LENGTH_SHORT).show()
    }

    private val linghtOff: (Boolean) -> Unit = {
        if (!it)
            timer?.cancel()
        if (hasFlashlight()) {
            isOn = false
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
                linghtOff22()
            else
                linghtOff23()
        } else
            Toast.makeText(context, "该设备没有闪光灯", Toast.LENGTH_SHORT).show()
    }

    private val linghtOn22 = {
        val camera = Camera.open()
        val parameters = camera.parameters
        parameters.flashMode = Camera.Parameters.FLASH_MODE_TORCH
        camera.parameters = parameters
    }

    @RequiresApi(Build.VERSION_CODES.M)
    private val linghtOn23 = {
        try {
            var manager = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager
            manager.setTorchMode("0", true)
        } catch (e: NullPointerException) {
            e.printStackTrace()
        }
    }

    private val linghtOff22 = {
        val camera = Camera.open()
        val parameters = camera.parameters
        parameters.flashMode = Camera.Parameters.FLASH_MODE_OFF
        camera.parameters = parameters
    }

    @RequiresApi(Build.VERSION_CODES.M)
    private val linghtOff23 = {
        try {
            var manager = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager
            manager.setTorchMode("0", false)
        } catch (e: NullPointerException) {
            throw RuntimeException("请先调用init()方法初始化")
        }
    }

    @JvmStatic
    fun hasFlashlight(): Boolean =
        context.packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)

    class Timer(countDownInterval: Long, val tick: (Long) -> Unit) :
        CountDownTimer(Long.MAX_VALUE, countDownInterval) {
        override fun onFinish() {
            start()
        }

        override fun onTick(millisUntilFinished: Long) = tick(millisUntilFinished)
    }

}

java版本

import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.os.Build;
import android.os.CountDownTimer;
import android.widget.Toast;

import androidx.annotation.IntRange;
import androidx.annotation.RequiresApi;


public class FlashlightUtils {
    private static Context context;
    private static boolean isOpen = false;
    private static Camera camera;
    private static CameraManager manager;
    private static CountDownTimer timer;

    public static void init(Context context) {
        FlashlightUtils.context = context;
    }

    public static boolean isOpen() {
        return isOpen;
    }

    public static void linghtOn(){
        linghtOn(false);
    }

    public static void linghtOff(){
        linghtOff(false);
    }

    public static void sos(@IntRange(from = 1,to = 6) int speed){
        //先关闭闪光灯
        linghtOff(false);
        if(timer != null)
            timer.cancel();
        timer =getTimer(speed);
        timer.start();
    }

    public static void offSos(){
        linghtOff(false);
    }


    private static void linghtOn(boolean isSos) {
        if (!isSos) {
            if(timer != null)
                timer.cancel();
        }

        if (hasFlashlight()) {
            isOpen = true;
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
                linghtOn22();
            else
                linghtOn23();
        } else Toast.makeText(context, "该设备没有闪光灯", Toast.LENGTH_SHORT).show();


    }

    private static void linghtOff(boolean isSos) {
        if (!isSos) {
            if(timer != null)
                timer.cancel();
        }

        if (hasFlashlight()) {
            isOpen = false;
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
                linghtOff22();
            else
                linghtOff23();
        } else Toast.makeText(context, "该设备没有闪光灯", Toast.LENGTH_SHORT).show();


    }

    private static CountDownTimer getTimer(int speed){
        long countDownInterval = (long)(1500/speed);
        return new CountDownTimer(Long.MAX_VALUE,countDownInterval){
            @Override
            public void onTick(long millisUntilFinished) {
                if (isOpen) linghtOff(true); else linghtOn(true);
            }

            @Override
            public void onFinish() {
                start();
            }
        };
    }


    private static void linghtOn22() {
        if (camera == null)
            camera = Camera.open();
        Camera.Parameters parameters = camera.getParameters();
        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
        camera.setParameters(parameters);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private static void linghtOn23() {
        try {
            if (manager == null)
                manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
            manager.setTorchMode("0", true);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    private static void linghtOff22() {
        if (camera == null)
            camera = Camera.open();
        Camera.Parameters parameters = camera.getParameters();
        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
        camera.setParameters(parameters);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private static void linghtOff23() {
        try {
            if (manager == null)
                manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
            manager.setTorchMode("0", false);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断是否有闪光灯
     *
     * @return
     */
    public static Boolean hasFlashlight() {
        return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
    }

}

猜你喜欢

转载自blog.csdn.net/jingzz1/article/details/105787463