Android 判断设备是否有可用的摄像头

fun checkCameraEnable(): Boolean {
            var canUse = false
            var mCamera: Camera? = null

            try {
                mCamera = Camera.open(0)
                val mParameters = mCamera.parameters
                mCamera.parameters = mParameters
            } catch (e: java.lang.Exception) {
                canUse = false
            }

            if (mCamera != null) {
                mCamera.release()
                canUse = true
            }

            return canUse

        }

更靠谱的方式如下

fun checkCameraEnable(): Boolean {
            var result: Boolean
            var camera: Camera? = null
            try {
                camera = Camera.open()
                if (camera == null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
                    var connected = false
                    for (camIdx in 0 until Camera.getNumberOfCameras()) {
                        try {
                            camera = Camera.open(camIdx)
                            connected = true
                        } catch (e: java.lang.RuntimeException) {
                        }
                        if (connected) {
                            break
                        }
                    }
                }
                val supportedPreviewSizes = camera?.parameters?.supportedPreviewSizes
                result = supportedPreviewSizes != null
                camera?.startPreview()
            } catch (e: java.lang.Exception) {
                result = false
            } finally {
                camera?.release()
            }
            return result
        }
    }
0 0 vote
Article Rating
Subscribe
提醒
guest
0 评论
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x