Android camera2: java.lang.IllegalStateException: maxImages (1) 已经获取,在获取更多之前调用#close

Android camera2: java.lang.IllegalStateException: maxImages (1) has already been acquired, call #close before acquiring more

您好,无法解决此问题。

我已经在 ImageAvailable 回调中调用了 imageReader.close,但仍然有错误:

java.lang.IllegalStateException: maxImages (1) has already been acquired, call #close before acquiring more.

我的代码在这里:

private ImageReader.OnImageAvailableListener imageAvailableListener = new ImageReader.OnImageAvailableListener()
{
    @Override
    public void onImageAvailable(ImageReader reader) {
        Image img = mReader.acquireLatestImage();

        mReader.close();
    }

};

ps。我也使用参数 reader 但似乎没有解决问题

好的,我的问题已经解决了。我需要关闭 img 对象而不是 ImageReader。

    private ImageReader.OnImageAvailableListener imageAvailableListener = new ImageReader.OnImageAvailableListener() {
    @Override
    public void onImageAvailable(ImageReader reader) {
        String status = Environment.getExternalStorageState();
        if (!status.equals(Environment.MEDIA_MOUNTED)) {
            Toast.makeText(getApplicationContext(), "your SD card is not available", Toast.LENGTH_SHORT).show();
            return;
        }
        Image image = reader.acquireNextImage();
        ByteBuffer buffer = image.getPlanes()[0].getBuffer();
        byte[] data = new byte[buffer.remaining()];
        buffer.get(data);
        image.close();//after you use the image's content ,you can close it
        String filePath = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/";
        String picturePath = System.currentTimeMillis() + ".jpg";
        imgFile = new File(filePath, picturePath);
        Uri uri = Uri.fromFile(imgFile);
        try {//Store to folder
            FileOutputStream fileOutputStream = new FileOutputStream(imgFile);
            fileOutputStream.write(data);
            fileOutputStream.close();


        } catch (IOException e) {
            e.printStackTrace();
        }
        startEditPictureActivity(uri, imgFile);


    }
};

close() 需要在 acquireLatestImage() returns.

Image 对象上调用

因此,从 OP 在他的样本中实现 onImageAvailable() 开始,只需在 acquireLatestImage() 之后添加 .close() 就可以了。
像这样:

public void onImageAvailable(ImageReader reader) {
    Image image = reader.acquireLatestImage().close(); // Note the added `close()` call.
}

我还应该补充一点,image 在您对其调用 close() 后将不再可用 (请参阅 docs)。
所以我上面提到的解决方案会让你摆脱提到的异常 OP,但你也无法对 image 做任何事情。这显然很容易修复,方法是先用 image 做任何你想做的事,然后才调用 close()