Android UncaughtExceptionHandler 以完成应用程序

Android UncaughtExceptionHandler to finish app

我想在记录未处理的异常后关闭应用程序。在这里搜索后,我做了以下内容:

public class MyApplication extends Application {
    //uncaught exceptions
    private Thread.UncaughtExceptionHandler defaultUEH;

    // handler listener
    private Thread.UncaughtExceptionHandler _unCaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread thread, Throwable ex) {
            ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
            //logging code
            //..........

            //call the default exception handler
            defaultUEH.uncaughtException(thread, ex);

        }
    };

    public MyApplication() {
        defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(_unCaughtExceptionHandler);
    }
}

在调用 defaultUEH.uncaughtException(thread, ex); 之后,我尝试调用 System.exit()android.os.Process.killProcess(android.os.Process.myPid());(甚至我发现一些帖子被告知要同时使用两者)。问题是我出现黑屏,我必须使用 phone 任务管理器强制退出应用程序。我做错了什么?

此致

最后我通过 class 实现 Thread.UncaughtExceptionHandler 接口解决了这个问题:

public class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {

    private BaseActivity activity;
    private Thread.UncaughtExceptionHandler defaultUEH;

    public MyUncaughtExceptionHandler(BaseActivity activity) {
        this.activity = activity;
        this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
    }

    public void setActivity(BaseActivity activity) {
        this.activity = activity;
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {

        //LOGGING CODE
        //........

        defaultUEH.uncaughtException(thread, ex);

    }
}

BaseActivity 我添加了以下代码:

//exception handling
private static MyUncaughtExceptionHandler _unCaughtExceptionHandler;

@Override
protected void onCreate(Bundle savedInstance) {
    super.onCreate(savedInstance);

    if(_unCaughtExceptionHandler == null)
        _unCaughtExceptionHandler = new MyUncaughtExceptionHandler(this);
    else
        _unCaughtExceptionHandler.setActivity(this);

    if(Thread.getDefaultUncaughtExceptionHandler() != _unCaughtExceptionHandler)
        Thread.setDefaultUncaughtExceptionHandler(_unCaughtExceptionHandler);
}

我知道它与问题中的代码相同,但不知何故它现在可以工作了。当我有更多空闲时间时,我会深入研究以找到根本原因 post 它