Search code examples
androidandroid-camerax

How to prevent CameraX from turning while


I build an app using CameraX codelab example, that is orking fine, but once my mobile gone into sleep and screen turned off, the CameraX transmittion had not been resumed after returning the mobile to normal status, and the CameraX screen remain white?

UPDATE

Sorry, it is not the Camera itself, The camera is invisible, and I've an image view, for which the image analyzer is displaying what is seen in the camera.

It look the val bitmap = view_finder.bitmap ?: return@Analyzer is returning null in my code below once the mobile goes in sleep.


   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)
    }

Solution

  • I also had the same issue and this solution worked for me. We can add the following line of code in onCreate(), to keep the device awake

    window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
    

    Here is the reference link from docs https://developer.android.com/training/scheduling/wakelock