Search code examples
javaandroidandroid-camera2

Camera2 API Working Only for First 5 Pictures


I have a problem with android camera2. I started from camera2Basic and changed it so that preview and capture takes manual pictures. So I changed CameraDevice.TEMPLATE_PREVIEW and CameraDevice.TEMPLATE_STILL_CAPTURE both to CameraDevice.TEMPLATE_MANUAL.

And I removed the preview callback, because without autofocus there is no need for it. So here is how I take a picture:

final CameraCaptureSession.CaptureCallback captureCallback
                = new CameraCaptureSession.CaptureCallback() {

            @Override
            public void onCaptureCompleted(@NonNull CameraCaptureSession session,
                                           @NonNull CaptureRequest request,
                                           @NonNull TotalCaptureResult result) {
                showToast("Saved");
                unlockFocus();
            }
        };

mCaptureSession.stopRepeating();
mCaptureSession.abortCaptures();
mCaptureSession.capture(mCaptureRequest, captureCallback, null);

And in unlockFocus:

mCaptureSession.capture(mPreviewRequest, null, mBackgroundHandler);
mCaptureSession.setRepeatingRequest(mPreviewRequest, mPreviewCaptureCallback,
                mBackgroundHandler);

But it works for 5 pictures every time, and then it never goes in onCaptureCompleted in the callback and I can't figure out why.

Can someone help me with this ?

EDIT:

captureCallback's onCaptureFailed says that the image has been taken but the capture failed with reason == 0 (Error in the framework but I don't know where, and how it could even work for 5 first captures) and the sequence id always go up by two when taking a picture.

So it means that the error occur whenever seqid > 10, is there a link ?


Solution

  • So as @Alex Cohn said, I was just forgetting to close the image on the ImageReader, and was searching the problem somewhere else.

    Here is the corrected ImageReader.OnImageAvailableListener with no processing of the output image as it was just a test.

    private final ImageReader.OnImageAvailableListener mOnImageAvailableListener
            = new ImageReader.OnImageAvailableListener() {
    
        @Override
        public void onImageAvailable(ImageReader reader) {
            Image image = reader.acquireNextImage();
            image.close();
        }
    
    };