java.lang.IllegalStateException:CameraX尚未初始化

时间:2019-05-20 20:23:27

标签: android android-camerax

我正在关注Google Codelab about CameraX

在添加“摄像机预览”这一部分时,我是这样做的:

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

        val preview = Preview(previewConfig)

        preview.setOnPreviewOutputUpdateListener { previewOutput ->
            val parent = previewView.parent as ViewGroup
            parent.removeView(previewView)
            parent.addView(previewView, 0)

            previewView.surfaceTexture =     previewOutput.surfaceTexture
        updateTransform()
        }


        CameraX.bindToLifecycle(this, preview)

然后出现以下错误:

java.lang.ExceptionInInitializerError
        at androidx.camera.core.Preview.<clinit>(Preview.java:55)
        at com.grow.vision.ImagePreviewActivity.startCamera(ImagePreviewActivity.kt:120)
        at com.grow.vision.ImagePreviewActivity.access$startCamera(ImagePreviewActivity.kt:28)
        at com.grow.vision.ImagePreviewActivity$onCreate$1.run(ImagePreviewActivity.kt:140)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7032)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
     Caused by: java.lang.IllegalStateException: CameraX not initialized yet.
        at androidx.camera.core.CameraX.getCameraDeviceSurfaceManager(CameraX.java:485)
        at androidx.camera.core.CameraX.getSurfaceManager(CameraX.java:282)
        at androidx.camera.core.Preview$Defaults.<clinit>(Preview.java:416)
        at androidx.camera.core.Preview.<clinit>(Preview.java:55)

似乎我需要以某种方式初始化CameraX,但是代码实验室或CameraX文档均未引用此类内容。

以前有人遇到过这个问题吗?

2 个答案:

答案 0 :(得分:2)

我很确定我找到了问题。 您是否将Camera2添加到依赖项?我忽略了它,认为没有必要,但这已在指南中。我添加了它,该错误停止了。

def camerax_version = "1.0.0-alpha01"
implementation "androidx.camera:camera-core:${camerax_version}"
implementation "androidx.camera:camera-camera2:${camerax_version}"

答案 1 :(得分:0)

您的代码看起来与我的代码完全相同,除了我的代码在初始化CameraX.unbindAll()并调用Preview之前在顶部有一个CameraX.bindtoLifeCycle()调用。我记得看到过类似您在添加CameraX.unbindAll()之前发布的错误的信息,因此请尝试一下吗?