AsyncTask 中的 openCamera returns "IllegalArgumentException"
openCamera in AsyncTask returns "IllegalArgumentException"
我正在尝试创建一个 AsyncTask,它将在后台拍照,但我收到
java.lang.IllegalArgumentException: Handler argument is null, but no looper exists in the calling thread
在 doInBackgroung 方法中我有:
@Override
protected String doInBackground(Object[] objects) {
startBackgroundThread();
openCamera();
takePicture();
return "Executed";
}
然后在openCamera方法中:
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();
}
}
有什么建议可以解决这个问题吗?
编辑: 忘了说当我只使用普通 Activity 时应用程序工作正常,但现在我想将该相机代码移动到 AsyncTask 中, 所以它在后台运行。
AsyncTask
旨在用于短期操作,不在内部使用相机 API 所需的 Looper
。可以改用 HandlerThread
,或者您自己管理 Looper
的 Thread
。
不过,在使用后台线程时,您可能 运行 遇到与 Android M+ 相关的其他电源管理问题。为了延长电池寿命,对后台操作进行了限制。请确保您需要在后台使用相机。
我正在尝试创建一个 AsyncTask,它将在后台拍照,但我收到
java.lang.IllegalArgumentException: Handler argument is null, but no looper exists in the calling thread
在 doInBackgroung 方法中我有:
@Override
protected String doInBackground(Object[] objects) {
startBackgroundThread();
openCamera();
takePicture();
return "Executed";
}
然后在openCamera方法中:
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();
}
}
有什么建议可以解决这个问题吗?
编辑: 忘了说当我只使用普通 Activity 时应用程序工作正常,但现在我想将该相机代码移动到 AsyncTask 中, 所以它在后台运行。
AsyncTask
旨在用于短期操作,不在内部使用相机 API 所需的 Looper
。可以改用 HandlerThread
,或者您自己管理 Looper
的 Thread
。
不过,在使用后台线程时,您可能 运行 遇到与 Android M+ 相关的其他电源管理问题。为了延长电池寿命,对后台操作进行了限制。请确保您需要在后台使用相机。