Android Camera disable stopPreview on takePicture

2019-08-21 10:19发布

问题:

I'm trying to build an app which uses the camera API to take one picture every second for 10 seconds. I followed the tutorial in this link Android Camera API and modified the code to get my list of pictures (see code below). Everything worked perfectly...

Now, the problem is (I suppose) on takePicture method because it stops the preview, I need to start it again in the callback onPictureTaken which causes a little moment of screen freeze.

private void initializeCamera() {
    // Create an instance of Camera
    mCamera = getCameraInstance();

    // Create our Preview view and set it as the content of our activity.
    CameraPreview mPreview = new CameraPreview(this, mCamera);
    FrameLayout preview = findViewById(R.id.camera_preview);
    preview.addView(mPreview);
    mCamera.setPreviewCallback(new Camera.PreviewCallback() {
        @Override
        public void onPreviewFrame(byte[] bytes, Camera camera) {
            startRecognition();
        }
    });
}


private PictureCallback mPicture = new PictureCallback() {
    @Override
    public void onPictureTaken(byte[] data, Camera camera) {
        mCamera.startPreview(); // <----- Restart preview.. stop freeze
        // Task to detect an object in the picture.. Do something
    }
};


public void startRecognition() {
    if (SystemClock.elapsedRealtime() - startedTime > 10000) {
        // Detection has failed.. Do something
    }
    else {
        // Get a frame each second
        if (SystemClock.elapsedRealtime() - elapsedTime > 1000) {
            elapsedTime = SystemClock.elapsedRealtime();
            mCamera.takePicture(null, null, mPicture);  // <---- Take picture but stop preview
        }
    }
}

From Android Camera doc:

8) After taking a picture, preview display will have stopped. To take more photos, call startPreview() again first.

Is there a way to disable the stopPreview, or anything else that this method does, when I take the picture?

Thank you for your help.

回答1:

Maybe for you the resolution delivered in onPreviewFrame() can be enough? Then, there is no need to restart the camera after 'taking a picture'. The live preview will not freeze.

If you target devices with API >= 21 (Lollipop), you should use the new camera2 API instead of the deprecated Camera API. The new API has many improvements, and among them - it can help with smooth multi-image capture.

Even if you are stuck with old API, there are some improvements to make.

One of the problems with your existing code is that it works with the camera device on UI thread. Rather, use a background HandlerThread to open the camera, and also make sure that onPictureTaken() restarts preview and returns iommediately, offloading all processing to yet another worker thread.