7

我正在关注这个关于 CameraX 的 Google Codelab

当我开始添加相机预览时,我会这样做:

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,但 codelab 或 CameraX 文档都没有引用类似的东西。

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

4

2 回答 2

16

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

def camerax_version = "1.0.0-alpha01"
implementation "androidx.camera:camera-core:${camerax_version}"
implementation "androidx.camera:camera-camera2:${camerax_version}"
于 2019-05-22T17:41:14.943 回答
0

你的代码看起来和我的一模一样,除了我在初始化和调用CameraX.unbindAll()之前在顶部有一个调用。我记得在我添加之前看到你发布的错误,所以试试看?PreviewCameraX.bindtoLifeCycle()CameraX.unbindAll()

于 2019-05-22T12:38:49.803 回答