Search code examples
androidandroid-asynctaskandroid-camera2

openCamera in AsyncTask returns "IllegalArgumentException"


I am trying to create an AsyncTask which will take pictures in background, but I am receiving

java.lang.IllegalArgumentException: Handler argument is null, but no looper exists in the calling thread

In the doInBackgroung method I've got:

    @Override
protected String doInBackground(Object[] objects) {
    startBackgroundThread();
    openCamera();
    takePicture();
    return "Executed";
}

and then in the openCamera method:

private void openCamera() {
    CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
    try{
        cameraId = manager.getCameraIdList()[1];
        CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
        StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
        assert map != null;
        imageDimension = map.getOutputSizes(SurfaceTexture.class)[0];

        manager.openCamera(cameraId,stateCallback,null); //It is breaking here

    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}

Any suggestion how can I solve this ?

Edit: Forgot to mention that the application works fine when I am using just a normal Activity, but now I want to move that camera code into and AsyncTask, so it runs in background.


Solution

  • AsyncTask is intended to be used for short lived operations and doesn't use a Looper internally, which is needed for the camera APIs. A HandlerThread could be used instead, or a Thread where you manage the Looper yourself.

    You'll likely run into other power management related issues with Android M+ when using a background thread, though. There are limits put on background operations in order to conserve battery life. Be sure you need to use the camera in the background.