如何实现 uncaughtException android [英] how to implement uncaughtException android

查看:13
本文介绍了如何实现 uncaughtException android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了这个Android:如何自动重启应用程序被强制关闭"了?

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

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

谢谢

推荐答案

您可以在应用程序扩展类中捕获所有未捕获的异常.在异常处理程序中对异常执行一些操作并尝试设置 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);
    }
}

这篇关于如何实现 uncaughtException android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆