首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >安卓UncaughtExceptionHandler不工作

安卓UncaughtExceptionHandler不工作
EN

Stack Overflow用户
提问于 2015-03-04 00:15:34
回答 2查看 2.4K关注 0票数 4

我正在创建一个启动器。有时我会遇到错误,当然我必须修复它们,但我正在尝试对我的整个应用程序使用UncaughtExceptionHandler。

为了做到这一点,我使用这个类:

代码语言:javascript
复制
  public class clsMyApplication extends Application 
  {
     // uncaught exception handler variable
     private UncaughtExceptionHandler defaultUEH;

     // handler listener
     private Thread.UncaughtExceptionHandler _unCaughtExceptionHandler = new Thread.UncaughtExceptionHandler() 
     {  @Override public void uncaughtException(Thread thread, Throwable ex) 
        {
           try
           {  Save a log file with the error and 
              save preferences indicating there was an error to display the next start up.
           }
           catch(Exception e)
           {

           }



           //Alarm to restart app:
           PendingIntent myActivity = PendingIntent.getActivity(clsMyApplication.this, 192837, new Intent(clsMyApplication.this, clsMyMainActivity.class), PendingIntent.FLAG_ONE_SHOT);
           AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
           alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 5000, myActivity );
           System.exit(2);


           // re-throw critical exception further to the os (important)
           defaultUEH.uncaughtException(thread, ex);
        }
     };

     public clsMyApplication() 
     {  
        defaultUEH = Thread.getDefaultUncaughtExceptionHandler();

        // setup handler for uncaught exception 
        Thread.setDefaultUncaughtExceptionHandler(_unCaughtExceptionHandler);      
     }


  }

我还将此类添加到清单中,如下所示:

代码语言:javascript
复制
<application       
    android:name=".clsMyApplication"         
    ....

但是我仍然得到了Android的异常。我不能让他们使用这个类。有什么帮助吗?

EN

回答 2

Stack Overflow用户

发布于 2015-03-04 00:32:08

将这行代码添加到任何方法中(最好是在OnCreate活动中)

代码语言:javascript
复制
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread thread, Throwable t) {
            //Do something
        }
    });
票数 1
EN

Stack Overflow用户

发布于 2015-04-10 10:32:58

我猜您可能没有处理覆盖方法uncaughtException(Thread thread, Throwable t){}中的异常

在我的项目中,我通常会在这里处理那些意外的异常,而不是由系统来处理。

代码语言:javascript
复制
@Override
public void uncaughtException(Thread thread, Throwable ex) {
    if (!handleException(ex) && mDefaultHandler != null) {
        // default exception handler
        mDefaultHandler.uncaughtException(thread, ex);
    } else {
        // exit program
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28836600

复制
相关文章

相似问题

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