美文网首页安卓开发
安卓开发手电筒应用(打开或关闭闪光灯)

安卓开发手电筒应用(打开或关闭闪光灯)

作者: 蓝不蓝编程 | 来源:发表于2020-08-06 20:06 被阅读0次

用途

打开或关闭闪光灯,用于手电筒应用.

主要代码

object FlashUtils {
    private lateinit var manager: CameraManager
    private lateinit var mCamera: Camera
    private lateinit var mContext: Context
    private var status = false //记录手电筒状态
    fun init(context: Context) {
        mContext = context
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            manager = mContext.getSystemService(Context.CAMERA_SERVICE) as CameraManager
        }
    }

    //打开手电筒
    fun open() {
        if (status) { //如果已经是打开状态,不需要打开
            return
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            try {
                manager.setTorchMode("0", true)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        } else {
            val packageManager = mContext.packageManager
            val features = packageManager.systemAvailableFeatures
            for (featureInfo in features) {
                if (PackageManager.FEATURE_CAMERA_FLASH == featureInfo.name) { // 判断设备是否支持闪光灯
                    val parameters = mCamera.parameters
                    parameters.flashMode = Camera.Parameters.FLASH_MODE_TORCH
                    mCamera.parameters = parameters
                    mCamera.startPreview()
                }
            }
        }
        status = true //记录手电筒状态为打开
    }

    //关闭手电筒
    fun close() {
        if (!status) { //如果已经是关闭状态,不需要打开
            return
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            try {
                manager.setTorchMode("0", false)
            } catch (e: CameraAccessException) {
                e.printStackTrace()
            }
        } else {
            mCamera.stopPreview()
            mCamera.release()
        }
        status = false //记录手电筒状态为关闭
    }
}

调用代码:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        FlashUtils.init(this)
        flashSwitch.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                FlashUtils.open()
            } else {
                FlashUtils.close()
            }
        }
    }
}

源代码

https://gitee.com/cxyzy1/flashlight

相关文章

网友评论

    本文标题:安卓开发手电筒应用(打开或关闭闪光灯)

    本文链接:https://www.haomeiwen.com/subject/qmhtdktx.html