前提

首先,我们肯定要在Application里面注册一个CrashHandler,监听应用crash

public class TestApplication extends MultiDexApplication {    private static TestApplication mInstance;    @Override    public void onCreate() {        super.onCreate();        Thread.setDefaultUncaughtExceptionHandler(new CrashHandler());          }

然后在这个CrashHandler 想办法重启应用。有两种方法如下:

方法1.通过AlarmManager

      public class CrashHandler implements Thread.UncaughtExceptionHandler {    @Override    public void uncaughtException(Thread t, Throwable e) {        //重启app        /**         * 这种方式 功能是可以达成         * 但是有问题就是如果说你的app挂了 这时候会显示系统桌面         * 然后你的app有启动起来了         * 给人的感觉不太好         */        Intent intent = new Intent();        Context context = TestApplication.getInstance();        intent.setClass(context, MainActivity.class);        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);        context.startActivity(intent);        PendingIntent pendingIntent = PendingIntent.getActivity(context,0,intent,PendingIntent.FLAG_ONE_SHOT);        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);        alarmManager.set(AlarmManager.RTC,System.currentTimeMillis() + 100,pendingIntent);        Process.killProcess(Process.myPid());        System.exit(0);    }}

方法2:

使用第三方库

    implementation 'com.jakewharton:process-phoenix:2.0.0'
public class CrashHandler implements Thread.UncaughtExceptionHandler {    @Override    public void uncaughtException(Thread t, Throwable e) {        ProcessPhoenix.triggerRebirth(TestApplication.getInstance());    }}

这个第三方库的原理是:
当app 崩溃的时候,ProcessPhoenix.triggerRebirth(TestApplication.getInstance());就会触发启动另外一个进程的Activity,然后把当前崩溃的进程结束掉。在新进程的Activity里面,把应用在自己的进程里面的启动起来。

更多相关文章

  1. android获取sd卡路径方法:
  2. android中常见的二种数据解析方法----XML和Json
  3. Android SDK Manager无法更新解决方法
  4. Android Timer 更好方法
  5. 删除android ScrollView边界阴影方法
  6. Android显示网络图片相关实现方法浅谈
  7. android 中Drawable跟Bitmap转换及常用于图片相关操作方法 - And
  8. Android跨进程通信

随机推荐

  1. android 静默安装
  2. 【Android(安卓)进阶】Android(安卓)Home
  3. Android学习笔记35——ProgressBar进度控
  4. 早日下班小技巧,建议收藏哦!2020最新Androi
  5. Android(安卓)Visible属性学习
  6. Android利用DownloadManager实现文件下载
  7. Unity同步/异步调用Android的方法实例
  8. Android(安卓)Handler,Message,MessageQu
  9. Android开发规范:API接口安全设计规范
  10. android java 小型知识点