我正在尝试将Camera2 api集成到我的应用程序中。某些设备出现崩溃。我在Stackoverflow上尝试了一些建议,但这些对我没有帮助。如何解决这个问题?
OnPause和OnStop of Activty:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_take_picture_new);
startBackgroundThread();
}
@Override
public void onStop() {
super.onStop();
closeCamera();
}
@Override
protected void onPause() {
Log.e(TAG, "onPause");
//closeCamera();
stopBackgroundThread();
super.onPause();
}
private void closeCamera() {
mCameraOpened = false;
if (null != cameraDevice) {
cameraDevice.close();
cameraDevice = null;
}
if (null != imageReader) {
imageReader.close();
imageReader = null;
}
}
protected void stopBackgroundThread() {
mBackgroundThread.quitSafely();
try {
mBackgroundThread.join();
mBackgroundThread = null;
mBackgroundHandler = null;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
protected void startBackgroundThread() {
mBackgroundThread = new HandlerThread("Camera Background");
mBackgroundThread.start();
mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
}
当我开始捕捉照片时,我得到了如下错误:
Fatal Exception: java.lang.IllegalArgumentException: Surface had no valid native Surface.
at android.hardware.camera2.legacy.LegacyCameraDevice.nativeGetSurfaceId(LegacyCameraDevice.java)
at android.hardware.camera2.legacy.LegacyCameraDevice.getSurfaceId(LegacyCameraDevice.java:658)
at android.hardware.camera2.legacy.LegacyCameraDevice.containsSurfaceId(LegacyCameraDevice.java:678)
at android.hardware.camera2.legacy.RequestThreadManager$2.onPictureTaken(RequestThreadManager.java:220)
at android.hardware.Camera$EventHandler.handleMessage(Camera.java:1248)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.hardware.camera2.legacy.CameraDeviceUserShim$CameraLooper.run(CameraDeviceUserShim.java:136)
at java.lang.Thread.run(Thread.java:818)
答案 0 :(得分:-1)
因为onStop()是在onPause()之后调用的。你试图阻止线程而不是关闭相机,但应该反之亦然。您应该在onPause()中调用closeCamera(),而在onStop()中调用stopBackgroundThread,如下所示:
@Override
protected void onPause() {
Log.e(TAG, "onPause");
closeCamera();
super.onPause();
}
@Override
public void onStop() {
stopBackgroundThread();
super.onStop();
}