CameraX-无法获取用例androidx.camera.core.Preview-4817149b-004d-42b8-a103-ea998038268b的相机ID-java.lang.IllegalArgumentException

时间:2019-08-02 04:20:22

标签: androidx android-jetpack android-camerax

从Google CodeLabs实现代码时,我在启动CameraActivity时收到此崩溃报告-CameraX - Google Code Labs

日志: 流程:in.novopay.novoloan,PID:5845     java.lang.IllegalArgumentException:无法获取用例androidx.camera.core.Preview-4817149b-004d-42b8-a103-ea998038268b的相机ID         在androidx.camera.camera2.impl.Camera2DeviceSurfaceManager.getCameraIdFromConfig(Camera2DeviceSurfaceManager.java:310)         在androidx.camera.camera2.impl.Camera2DeviceSurfaceManager.requiresCorrectedAspectRatio(Camera2DeviceSurfaceManager.java:268)         在androidx.camera.core.Preview.updateUseCaseConfig(Preview.java:387)         在androidx.camera.core.UseCase。(UseCase.java:92)         在androidx.camera.core.Preview。(Preview.java:99) 位于in.novopay.uicontrollibrary.activities.CameraActivity.startCamera(CameraActivity.kt:94)         位于in.novopay.uicontrollibrary.activities.CameraActivity.access $ startCamera(CameraActivity.kt:30)         在in.novopay.uicontrollibrary.activities.CameraActivity $ checkPermission $ 1.run(CameraActivity.kt:45)         在android.os.Handler.handleCallback(Handler.java:790)         在android.os.Handler.dispatchMessage(Handler.java:99)         在android.os.Looper.loop(Looper.java:164)         在android.app.ActivityThread.main(ActivityThread.java:7000)         在java.lang.reflect.Method.invoke(本机方法)         在com.android.internal.os.RuntimeInit $ MethodAndArgsCaller.run(RuntimeInit.java:441)         在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)      引起原因:java.lang.IllegalArgumentException:不存在该选项:Option {id = camerax.core.camera.lensFacing,valueClass = class androidx.camera.core.CameraX $ LensFacing,token = null}

// This is an arbitrary number we are using to keep tab of the permission
// request. Where an app has multiple context for requesting permission,
// this can help differentiate the different contexts
private const val REQUEST_CODE_PERMISSIONS = 10

// This is an array of all the permission specified in the manifest
private val REQUIRED_PERMISSIONS = arrayOf(Manifest.permission.CAMERA)

class CameraActivity : AppCompatActivity(), LifecycleOwner {

    lateinit var viewFinder: TextureView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_camera)

        viewFinder = findViewById(R.id.texture_view)
//        startCamera()
        checkPermission();
    }

    fun checkPermission() {
        if (allPermissionsGranted()) {
            viewFinder.post { startCamera() }
        } else {
            ActivityCompat.requestPermissions(
                    this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS)
        }

        // Every time the provided texture view changes, recompute layout
        viewFinder.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ ->
            updateTransform()
        }
    }

    /**
     * Process result from permission request dialog box, has the request
     * been granted? If yes, start Camera. Otherwise display a toast
     */
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {

        if (requestCode == REQUEST_CODE_PERMISSIONS) {
            if (allPermissionsGranted()) {
                viewFinder.post {
                    startCamera()
                }

            } else {
                Toast.makeText(this,
                        "Permissions not granted by the user.",
                        Toast.LENGTH_SHORT).show()
                finish()
            }
        }
    }

    /**
     * Check if all permission specified in the manifest have been granted
     */
    private fun allPermissionsGranted() = REQUIRED_PERMISSIONS.all {
        ContextCompat.checkSelfPermission(
                baseContext, it) == PackageManager.PERMISSION_GRANTED
    }

    private fun startCamera() {
        // Create configuration object for the viewfinder use case
        val previewConfig = PreviewConfig.Builder().apply {
            setTargetAspectRatio(Rational(1, 1))
            setTargetResolution(Size(640, 640))
        }.build()

        // Build the viewfinder use case
        val preview = Preview(previewConfig)

        // Every time the viewfinder is updated, recompute layout
        preview.setOnPreviewOutputUpdateListener {

            // To update the SurfaceTexture, we have to remove it and re-add it
            val parent = viewFinder.parent as ViewGroup
            parent.removeView(viewFinder)
            parent.addView(viewFinder, 0)

            viewFinder.surfaceTexture = it.surfaceTexture
            updateTransform()
        }

        // Bind use cases to lifecycle
        // If Android Studio complains about "this" being not a LifecycleOwner
        // try rebuilding the project or updating the appcompat dependency to
        // version 1.1.0 or higher.
        CameraX.bindToLifecycle(this, preview)
    }

    private fun updateTransform() {
        val matrix = Matrix()

        // Compute the center of the view finder
        val centerX = viewFinder.width / 2f
        val centerY = viewFinder.height / 2f

        // Correct preview output to account for display rotation
        val rotationDegrees = when(viewFinder.display.rotation) {
            Surface.ROTATION_0 -> 0
            Surface.ROTATION_90 -> 90
            Surface.ROTATION_180 -> 180
            Surface.ROTATION_270 -> 270
            else -> return
        }

        matrix.postRotate(-rotationDegrees.toFloat(), centerX, centerY)

        // Finally, apply transformations to our TextureView
        viewFinder.setTransform(matrix)
    }
}

1 个答案:

答案 0 :(得分:9)

val previewConfig = PreviewConfig.Builder().apply {
            setTargetAspectRatio(Rational(1,1))
            setTargetResolution(Size(640,640))
            setLensFacing(androidx.camera.core.CameraX.LensFacing.BACK)
        }.build()