Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android camera locked after force close

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?

like image 579
Martynas Jurkus Avatar asked Jun 26 '13 11:06

Martynas Jurkus


1 Answers

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();
like image 59
18446744073709551615 Avatar answered Sep 18 '22 12:09

18446744073709551615