如何实现uncaughtException android

Mik*_*ant 31 android exception-handling

我找到了这个 Android:如何在"强制关闭"后自动重启应用程序?

但我不知道在哪里以及如何放置警报管理器

谢谢

Max*_*xim 67

您可以在Application扩展类中捕获所有未捕获的异常.在异常处理程序中执行有关异常的操作并尝试设置AlarmManager以重新启动应用程序.这是我在我的应用程序中如何做的示例,但我只将异常记录到数据库.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)