【问题标题】:Android UncaughtExceptionHandler not workingAndroid UncaughtExceptionHandler 不起作用
【发布时间】:2025-11-24 13:10:02
【问题描述】:

我正在创建一个启动器。有时我有错误,当然我必须修复它们,但我正在尝试为我的整个应用程序使用 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 异常。我无法让他们使用这个类。有什么帮助吗?

【问题讨论】:

  • 您是否尝试覆盖 onCreate() 而不是使用构造函数? (即用public void onCreate()替换public clsMyApplication()
  • 我按照你的建议试过了,但是没用

标签: android uncaughtexceptionhandler


【解决方案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 中读取任何错误日志,而您可以在警告而不是错误中找到错误日志。
【解决方案2】:

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

Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {

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

【讨论】:

  • 抱歉,仍然失败