I have an application where I use devices camera.
Now I only release camera in normal flow.
@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
if(camera != null) {
camera.stopPreview();
camera.release();
}
}
Thus, then application exits in camera mode in unexpected way - i.e. Force Close (due to OutOfMemoryError
) - camera gets locked. And only way to release it is to restart device.
And after application is started I get:
RuntimeException: Fail to connect to camera service
How could I make sure, that camera is released in any case?
Since the best way to keep a portion of code so that you find it later is to publish it in the 'net,
private UnexpectedTerminationHelper mUnexpectedTerminationHelper = new UnexpectedTerminationHelper();
private class UnexpectedTerminationHelper {
private Thread mThread;
private Thread.UncaughtExceptionHandler mOldUncaughtExceptionHandler = null;
private Thread.UncaughtExceptionHandler mUncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable ex) { // gets called on the same (main) thread
XXXX.closeCamera(); // TODO: write appropriate code here
if(mOldUncaughtExceptionHandler != null) {
// it displays the "force close" dialog
mOldUncaughtExceptionHandler.uncaughtException(thread, ex);
}
}
};
void init() {
mThread = Thread.currentThread();
mOldUncaughtExceptionHandler = mThread.getUncaughtExceptionHandler();
mThread.setUncaughtExceptionHandler(mUncaughtExceptionHandler);
}
void fini() {
mThread.setUncaughtExceptionHandler(mOldUncaughtExceptionHandler);
mOldUncaughtExceptionHandler = null;
mThread = null;
}
}
and, in the appropriate places on the main thread:
mUnexpectedTerminationHelper.init();
and
mUnexpectedTerminationHelper.fini();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With