我是靠谱客的博主 聪明可乐,最近开发中收集的这篇文章主要介绍解决 CameraX 报错:Must call CameraX.initialize() first,觉得挺不错的,现在分享给大家,希望可以做个参考。
概述
报错信息如下:
Caused by: java.lang.IllegalStateException: java.util.concurrent.ExecutionException: java.lang.IllegalStateException: Must call CameraX.initialize() first
at androidx.camera.core.CameraX.waitInitialized(CameraX.java:862)
at androidx.camera.core.CameraX.checkInitialized(CameraX.java:753)
at androidx.camera.core.CameraX.getSurfaceManager(CameraX.java:534)
at androidx.camera.core.Preview$Defaults.<clinit>(Preview.java:491)
at androidx.camera.core.Preview.<clinit>(Preview.java:137)
at androidx.camera.core.Preview$Builder.build(Preview.java:591)
at ltd.xsfu.app.happlyface.MainActivity.onCreate(MainActivity.kt:39)
首先,项目必须依赖以下4个 camearx 库:
dependencies {
val cameraXVersion = "1.0.0-alpha10"
implementation("androidx.camera:camera-core:$cameraXVersion")
implementation("androidx.camera:camera-camera2:$cameraXVersion")
implementation("androidx.camera:camera-lifecycle:$cameraXVersion")
implementation("androidx.camera:camera-view:1.0.0-alpha07")
}
然后,自定义的 Application 必须实现 CameraXConfig.Provider
接口:
class HappyFaceApplication : Application(), CameraXConfig.Provider {
override fun onCreate() {
super.onCreate()
}
override fun getCameraXConfig(): CameraXConfig {
return Camera2Config.defaultConfig()
}
}
最后,ProcessCameraProvider.getInstance(this)
必须要在构造 Preview 、ImageCapture、ImageAnalysis 之前:
// 该方法一定要在构造 Preview 、ImageCapture、ImageAnalysis 之前
cameraProviderFuture = ProcessCameraProvider.getInstance(this)
// 预览
val preview = Preview.Builder().build()
preview.setSurfaceProvider(viewBinding.previewView.previewSurfaceProvider)
// 拍照
val capture = ImageCapture.Builder().build()
// 分析
val analysis = ImageAnalysis.Builder().build()
// 可以放在需要的地方进行初始化
cameraProviderFuture.addListener(Runnable {
val cameraProvider = cameraProviderFuture.get()
cameraProvider.bindToLifecycle(
this@MainActivity as LifecycleOwner,
CameraSelector.DEFAULT_FRONT_CAMERA,
preview,
capture,
analysis
)
}, ContextCompat.getMainExecutor(this))
最后
以上就是聪明可乐为你收集整理的解决 CameraX 报错:Must call CameraX.initialize() first的全部内容,希望文章能够帮你解决解决 CameraX 报错:Must call CameraX.initialize() first所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复