Android应用程序中的UncaughtExceptionHandler用于结束应用程序。

7
我希望在未处理的异常被记录后关闭应用程序。在此搜索后,我执行了以下操作:
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());(甚至在一些帖子中找到建议同时使用两者)。问题是我得到了一个黑屏,只能通过手机任务管理器强制退出应用程序。我做错了什么?
谢谢!

为什么需要调用System.exit?如果您想关闭应用程序,只需在Activity上调用finish()即可。 - HendraWD
1
是的,但问题在于我在应用程序对象上捕获异常,而不是在活动中。 - cobolero
1个回答

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

我知道这是同样的代码,但现在它正在运行。当我有更多的空闲时间时,我会深入研究找到根本原因并发表它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接