首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >安卓UncaughtExceptionHandler完成应用

安卓UncaughtExceptionHandler完成应用
EN

Stack Overflow用户
提问于 2016-08-11 20:31:08
回答 1查看 3.4K关注 0票数 4

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

代码语言:javascript
复制
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()); (甚至我还发现了一些帖子,其中告诉我两者都要使用)。问题是我得到了一个黑屏,我不得不用手机任务管理器强制退出应用程序。我做错了什么?

问候

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-08-12 16:27:34

最后,我解决了这个问题,创建了一个实现Thread.UncaughtExceptionHandler接口的类:

代码语言:javascript
复制
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中,我添加了以下代码:

代码语言:javascript
复制
//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);
}

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38896483

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档