Android 闪光灯的打开和关闭

网上的方法大部分只支持 6.0 以下的手机,于是写了个兼容 6.0 以上手机的工具类:

class FlashUtils {

    companion object {
        fun get():FlashUtils = Holder.instance
    }

    private object Holder {
        val instance = FlashUtils()
    }

    private var isFlashOn = false
    fun toggle(context: Context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val camManager = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager
            val cameraId = camManager.cameraIdList[0]
            camManager.setTorchMode(cameraId, !isFlashOn)
            isFlashOn = !isFlashOn
        } else {
            var camera = Camera.open()
            var parameters = camera.parameters
            if (isFlashOn) {
                parameters.flashMode = Camera.Parameters.FLASH_MODE_OFF
            } else {
                parameters.flashMode = Camera.Parameters.FLASH_MODE_TORCH
            }
            isFlashOn = !isFlashOn
            camera.parameters = parameters
        }
    }
}

需要 2 个权限:



你可能感兴趣的:(Android 闪光灯的打开和关闭)