1

我使用CameraX codelab示例构建了一个应用程序运行良好,但是一旦我的手机进入睡眠状态并关闭屏幕,将手机恢复正常状态后CameraX传输没有恢复,并且CameraX屏幕保持白色?

更新

抱歉,这不是相机本身,相机是不可见的,我有一个图像视图,图像分析器正在显示相机中看到的内容。

val bitmap = view_finder.bitmap ?: return@Analyzer一旦手机进入睡眠状态,它看起来在我下面的代码中返回 null。


   private lateinit var viewFinder: TextureView
    private fun startCamera() {
        val previewConfig = PreviewConfig.Builder().apply {
            setTargetAspectRatio(Rational(1, 1))
            setTargetResolution(Size(640, 640))
        }.build()
        val preview = Preview(previewConfig)
        preview.setOnPreviewOutputUpdateListener {
            val parent = viewFinder.parent as ViewGroup
            parent.removeView(viewFinder)
            parent.addView(viewFinder, 0)
            viewFinder.surfaceTexture = it.surfaceTexture
            updateTransform()
        }

        val imageCaptureConfig = Builder()
            .apply {
                setTargetAspectRatio(Rational(1, 1))
                setCaptureMode(ImageCapture.CaptureMode.MIN_LATENCY)
            }.build()

        val imageCapture = ImageCapture(imageCaptureConfig)
        findViewById<ImageButton>(R.id.capture_button).setOnClickListener {
            val file = File(externalMediaDirs.first(),
                "${System.currentTimeMillis()}.jpg")
            imageCapture.takePicture(file,
                object : ImageCapture.OnImageSavedListener {
                    override fun onError(error: ImageCapture.UseCaseError,
                                         message: String, exc: Throwable?) {
                        val msg = "Photo capture failed: $message"
                        Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
                        Log.e("CameraXApp", msg)
                        exc?.printStackTrace()
                    }

                    override fun onImageSaved(file: File) {
                        val msg = "Photo capture succeeded: ${file.absolutePath}"
                        Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
                        Log.d("CameraXApp", msg)
                    }
                })
        }

        // Setup image analysis pipeline that computes average pixel luminance
        val analyzerConfig = ImageAnalysisConfig.Builder().apply {
            val analyzerThread = HandlerThread(
                "LuminosityAnalysis").apply { start() }
            setCallbackHandler(Handler(analyzerThread.looper))
            setImageReaderMode(
                ImageAnalysis.ImageReaderMode.ACQUIRE_LATEST_IMAGE)
        }.build()

        val analyzerUseCase = ImageAnalysis(analyzerConfig).apply {

////// This is my own code that I added to the analyzer ///////
            analyzer = ImageAnalysis.Analyzer { image, rotationDegrees ->
                val bitmap = view_finder.bitmap ?: return@Analyzer
                scope.launch(Dispatchers.Unconfined) {
                    val mat = Mat()
                    Utils.bitmapToMat(bitmap!!, mat)
                    val detectedFaces = FaceDetection.detectFaces(bitmap!!)
                    println("Detected Faces = $detectedFaces")
                    Toast.makeText(
                        this@MainActivity, "Detected Faces = ${detectedFaces.toArray().size}",
                        Toast.LENGTH_SHORT
                    ).show()
                   if (detectedFaces.toArray().isNotEmpty()) {
                       val paint = Paint().apply {
                           isAntiAlias = true
                           style = Paint.Style.STROKE
                           color = Color.RED
                           strokeWidth = 10f
                       }

                       for (rect in detectedFaces.toArray()) {
                           bitmap?.let { Canvas(it) }?.apply {
                               drawRect(
                                   rect.x.toFloat(), // faceRectangle.left,
                                   rect.y.toFloat(), //faceRectangle.top,
                                   rect.x.toFloat() + rect.width,
                                   rect.y.toFloat() + rect.height,
                                   paint
                               )
                           }
                       }
                   }
                }

                runOnUiThread { imageView.setImageBitmap(bitmap) }
            }
        }

        CameraX.bindToLifecycle(
            this, preview, imageCapture, analyzerUseCase)
    }
4

1 回答 1

0

我也有同样的问题,这个解决方案对我有用。我们可以在 onCreate() 中添加以下代码行,以保持设备唤醒

window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)

这是来自文档 https://developer.android.com/training/scheduling/wakelock的参考链接

于 2021-04-06T07:14:09.680 回答