Android App异常退出时重新启动

在我们书写程序时,异常的出现时无处不在的。当程序出现异常时对用户来说肯定是不友好,所以在这里我们需要对我们程序的一个异常进行捕获,在Thread类中有一个UncaughtExceptionHandler接口,官方是这么介绍的:

Implemented by objects that want to handle cases where a thread is being terminated by an uncaught exception. Upon such termination, the handler is notified of the terminating thread and causal exception. If there is no explicit handler set then the thread’s group is the default handler.

意思大概就是说当我们程序被未捕获异常终止的情况的对象实现。当我们没有进行处理时,在运行时如果出现异常,就会在手机显示我们的应用程序异常终止,这种情况我们是最不想见到的了。所以在这里我们就可以通过这里来对我应用程序的异常进行监控,在这里我只是简单的进行处理,当发生异常时在重新启动我们的App。

首先我们需要自定义我们的Application,在我们的Application中去实现这个UncaughtExceptionHandler接口,代码如下:

public class MyApplication extends Application {

    private static MyApplication application;
    @Override
    public void onCreate() {
        super.onCreate();
        application = this;
        // 程序崩溃时触发线程  以下用来捕获程序崩溃异常
        Thread.setDefaultUncaughtExceptionHandler(handler); 
    }
   private Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            restartApp(); //发生崩溃异常时,重启应用
        }
    };
    private void restartApp() {
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent restartIntent = PendingIntent.getActivity(
                application.getApplicationContext(), 0, intent,Intent.FLAG_ACTIVITY_NEW_TASK);
        //退出程序
        AlarmManager mgr = (AlarmManager)application.getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000,
                restartIntent); // 1秒钟后重启应用

        //结束进程之前可以把你程序的注销或者退出代码放在这段代码之前
        android.os.Process.killProcess(android.os.Process.myPid());
    }

}

对于Intent我想大家应该在熟悉不过了,但是对于PendingIntent 有可能你还是第一看到吧;Intent一般是用作Activity、Sercvice、BroadcastReceiver之间传递数据,而Pendingintent,一般用在 Notification上,可以理解为延迟执行的intent,PendingIntent是对Intent一个包装。所以它们两者的主要区别在于Intent的执行立刻的,而pendingIntent的执行不是立刻的。pendingIntent执行的操作实质上是参数传进来的Intent的操作,但是使用pendingIntent的目的在于它所包含的Intent的操作的执行是需要满足某些条件的。

pendingIntent主要的使用的地方和例子:通知Notificatio的发送,短消息SmsManager的发送和警报器AlarmManager的执行等等

在上面我们也可以看到PendingIntent调用getActivity方法有四个参数,那么这四个参数是什么呢,我们点击进去查看源码看到(Context context, int requestCode,Intent intent, @Flags int flags),这四个参数我想大家都熟悉我就不去介绍了。

至此我们就已经完成了当我们程序发生异常时,1s之后在重新启动我们的的App。(Application别忘记在清单文件中注册哟!)当然如果你想收集崩溃的错误信息,在我们第三的sdk就有开源的,具体的你可以自己去查找然后再集成到你的项目中,这样你就能更好的查看到你的应用在那出现错误,去解决达到更好的用户体验。

猜你喜欢

转载自blog.csdn.net/weixin_37185329/article/details/73089458