how to implement uncaughtException android

后端 未结 2 1750
野性不改
野性不改 2020-11-29 00:31

I found this Android: How to auto-restart application after it's been "force closed"?

but I don\'t know where and how to put the alarm manager

2条回答
  •  一整个雨季
    2020-11-29 01:33

    You can catch all uncaught exceptions in your Application extension class. In the exception handler do something about exception and try to set up AlarmManager to restart your app. Here is example how I do it in my app, but I only log exception to a db.

    public class MyApplication 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) {
    
                    // here I do logging of exception to a db
                    PendingIntent myActivity = PendingIntent.getActivity(getContext(),
                        192837, new Intent(getContext(), MyActivity.class),
                        PendingIntent.FLAG_ONE_SHOT);
    
                    AlarmManager alarmManager;
                    alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
                    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 
                        15000, myActivity );
                    System.exit(2);
    
                    // re-throw critical exception further to the os (important)
                    defaultUEH.uncaughtException(thread, ex);
                }
            };
    
        public MyApplication() {
            defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
    
            // setup handler for uncaught exception 
            Thread.setDefaultUncaughtExceptionHandler(_unCaughtExceptionHandler);
        }
    }
    

提交回复
热议问题