Android摄像头锁定强制关闭后,摄像头、Android

2023-09-04 06:31:28 作者:纠结的人生

我有,我用的设备摄像头的应用程序。

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();
    } 
} 

因此​​,在拍照模式中意想不到的方式,然后退出应用程序 - 即强制关闭(由于的OutOfMemoryError ) - 相机被锁定。并释放唯一的方法就是重新启动设备。

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.

和应用程序启动后,我得到: 的RuntimeException:无法连接到摄像机服务

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?

推荐答案

由于最好的方式来保持code的一部分,这样你以后发现这是在网发布,

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();

    mUnexpectedTerminationHelper.fini();