I am working on a modification of Google's Camera2 API example for Android, found here: https://github.com/googlesamples/android-Camera2Basic
I am uploading captured images to Cloudinary, and obviously need to do so in a background thread so the UI isn't blocked.
The problem I'm running into, however, is that the UI actually is blocked when the image is uploaded even though from what I understand, it shouldn't be, because the Handler is created with the Looper from a background thread like so:
private void startBackgroundThread() {
mBackgroundThread = new HandlerThread("CameraBackground");
mBackgroundThread.start();
mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
}
The ImageSaver class, which is responsible for writing the captured image to disk, is as follows:
private static class ImageSaver implements Runnable {
/**
* The JPEG image
*/
private final Image mImage;
/**
* The file we save the image into.
*/
private final File mFile;
public ImageSaver(Image image, File file ) {
mImage = image;
mFile = file;
}
@Override
public void run() {
ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
FileOutputStream output = null;
try {
output = new FileOutputStream(mFile);
output.write(bytes);
InputStream is = new ByteArrayInputStream(bytes);
Map uploadResult = CloudinaryManager.getInstance().uploader().upload(is, ObjectUtils.asMap(
"api_key", CloudinaryManager.CLOUDINARY_API_KEY,
"api_secret", CloudinaryManager.CLOUDINARY_SECRET_KEY
));
System.out.println("result");
} catch (IOException e) {
e.printStackTrace();
} finally {
mImage.close();
if (null != output) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The ImageSaver is added to the Handler here:
private final ImageReader.OnImageAvailableListener mOnImageAvailableListener
= new ImageReader.OnImageAvailableListener() {
@Override
public void onImageAvailable(ImageReader reader) {
mBackgroundHandler.post(new ImageSaver(reader.acquireNextImage(), mFile));
}
};
I would appreciate any help or advice to point me in the right direction.