Android UncaughtExceptionHandler未起作用

3

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

为此,我使用了这个类:

  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);      
     }


  }

我也将这个类添加到清单文件中,像这样:
<application       
    android:name=".clsMyApplication"         
    ....

但我仍然得到Android异常。使用这个类,我无法获取它们。有什么帮助吗?


您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Gorcyn
我按照你建议的尝试了,但是没有成功。 - Ton
2个回答

2
将此行代码添加到任何方法中(最好是在OnCreate活动中)
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {

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

抱歉,仍然失败。 - Ton

1
我猜你可能没有在重写方法 uncaughtException(Thread thread, Throwable t){} 中处理异常。
在我的项目中,通常我会在此处处理那些意外的异常,而不是由系统处理。
@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);
    }
}

然而,如果我这样做,我无法在 logcat 中读取任何错误日志,而你可以在警告中找到错误日志,而不是错误。 - Snk

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