美文网首页
如何更优雅的crash后重启app?

如何更优雅的crash后重启app?

作者: 许先森的许 | 来源:发表于2016-11-28 11:36 被阅读962次

    1、需求场景:

    app异常后直接crash,对用户不友好,希望发生异常时可以捕获异常并且重新启动app。

    补充一点:完美配合bugly异常上传,bugly工作人员回复只要UncaughtExceptionHandler的注册在bugly注册之前即可。

    2、实现方式:

    使用UncaughtExceptionHandler捕获异常,然后重新启动app。

    1、在你的Application实现 UncaughtExceptionHandler 接口:

    public class BaseApplication extends MultiDexApplication implements Thread.UncaughtExceptionHandler

    在onCreate方法中注册Thread.setDefaultUncaughtExceptionHandler(this);

    2、复写 public void uncaughtException(Thread thread, Throwable ex) 方法,在这个方法中做重新启动:

    @Override

    public void uncaughtException(Thread thread, Throwable ex) {

    if (null != ex && null != thread) {

    LoggerUtil.e("uncaughtException", "exception = " + ex.getMessage() + "|||| at Thread = " + thread.getName());

    }

    //do u want

    AppUtil.restartApp(mInstance, MainActivity.class, AppUtil.RESTART_DELAY_MILLIS);

    }

    3、重新启动实现:

    public static void restartApp(Application application, Class cls, long delayMillis) {

    Intent intent = new Intent(application.getApplicationContext(), cls);

    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    PendingIntent restartIntent = PendingIntent.getActivity(application.getApplicationContext(), 0, intent, 0);

    AlarmManager alarmManager = (AlarmManager) application.getSystemService(Context.ALARM_SERVICE);

    //延迟delayMillis毫秒执行操作

    alarmManager.set(AlarmManager.RTC, System.currentTimeMillis() + delayMillis, restartIntent);

    android.os.Process.killProcess(android.os.Process.myPid());

    }

    4、注意,以下方式均无法重新启动:

    1、Intent intent = new Intent(this, MainActivity.class);

    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);

    startActivity(intent);

    这个是因为没用PendingIntent的原因,想要启动app必须用PendingIntent。

    2、用Service的方式:用Intent传递包名和延迟时间,startService开启一个service,然后杀死进程,在service中利用包名启动app并且杀死service自己,不知道这个方式是不是因为用intent没用PendingIntent的原因。

    3、测试:

    某个页面throw new NullPointException(),进入页面app崩溃,然后被UncaughtExceptionHandler捕获后执行了重启操作。

    测试手机:MI4c 5.1; 华为 5.1;三星 5.0; 华为 4.4.2

    4、问题

    1、上面的方式成功实现了捕获异常并且重启app,使用的是AlarmManager定时操作,但是会发现重启的过程不是那么平滑,会有1-2秒的白屏页面,并且不同手机还会出现不同程度的第二次延迟重启,什么意思呢,就是第一次崩溃白屏2秒立刻就自动重启,重启后的app再崩溃白屏1秒后显示了桌面,2-4秒后才重启,这个延迟时间每个手机都不一样,但是都会有这个现象;

    2、于是我尝试修改AlarmManager延迟启动的时间改为不延迟,发现小米和华为没问题,三星无法重新启动了;

    相关文章

      网友评论

          本文标题:如何更优雅的crash后重启app?

          本文链接:https://www.haomeiwen.com/subject/akkopttx.html