Android UncaughtExceptionHandler完成应用程序

时间:2016-08-11 12:31:08

标签: android uncaughtexceptionhandler

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

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());(即使我发现有些帖子被告知同时使用这两个帖子)。问题是我得到一个黑屏,我不得不强迫应用程序退出电话任务管理器。我做错了什么?

此致

1 个答案:

答案 0 :(得分:0)

最后我解决了这个问题,制作了一个实现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);
}

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