且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何实现uncaughtException机器人

更新时间:2023-11-19 08:39:52

您可以赶上在你的应用程序扩展类的所有未捕获的异常。在异常处理程序做一些异常,并尝试建立AlarmManager重新启动应用程序。下面是例子,我怎么做我的应用程序,但我只记录异常到一个数据库。

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