运行时异常:启动预览失败

RuntimeException: startPreview failed

在 crashlytics 中获取下一个错误:

Fatal Exception: java.lang.RuntimeException: startPreview failed
       at android.hardware.Camera.startPreview(Camera.java)
       at com.google.android.gms.vision.CameraSource.start(CameraSource.java:24)
       at com.sai.authenticator.features.qr.QrScannerActivity.startCameraSource(QrScannerActivity.java:174)
       at com.sai.authenticator.features.qr.QrScannerActivity.access$onReceivedCodes(QrScannerActivity.java:54)
       at com.sai.authenticator.features.qr.QrScannerActivity$setupViewModel.onChanged(QrScannerActivity.java:100)
       at com.sai.authenticator.features.qr.QrScannerActivity$setupViewModel.onChanged(QrScannerActivity.java:54)
       at androidx.lifecycle.LiveData.considerNotify(LiveData.java:131)
       at androidx.lifecycle.LiveData.dispatchingValue(LiveData.java:149)
       at androidx.lifecycle.LiveData.setValue(LiveData.java:307)
       at androidx.lifecycle.MutableLiveData.setValue(MutableLiveData.java:50)
       at androidx.lifecycle.LiveData.run(LiveData.java:91)
       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:7081)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)

这是我的代码 QrScannerActivity.java:174:

看似万事俱备,万无一失,但错误却落空了。

不幸的是,我无法重现该错误,所以我假设表面可能为空,因此应用程序在启动时崩溃。 这就是我决定以这种方式更新代码的原因。

val holder = surfaceView?.holder
if (holder != null) cameraSource?.start(holder)
else this@QrScannerActivity.showWarningSnack(textResId = R.string.errors_failed_to_start_camera)