前提

首先,我们肯定要在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(安卓)内存笔记
  2. 2013.08.21——— android 四种启动模式
  3. Android跨进程通信
  4. android流量统计
  5. Android学习笔记之mainfest文件中android属性
  6. Android解决禁止使用http协议的方案
  7. 活动的启动模式汇总
  8. Android(安卓)系统启动过程
  9. Android学习笔记之mainfest文件中android属性

随机推荐

  1. 云关系型数据库(Relational Database Serv
  2. 云数据迁移(Cloud Data Migration,CDM)
  3. 弹性云服务器(Elastic Cloud Server,ECS)
  4. 云专线(Direct Connect,DC)
  5. 内容分发网络(Content Delivery Network,CD
  6. 虚拟私有云(Virtual Private Cloud,VPC)
  7. SpringMVC @Value注解无法获取值 报Illeg
  8. 弹性公网IP(Elastic IP,EIP)
  9. 弹性负载均衡(Elastic Load Balance,ELB)
  10. 云服务器备份(Cloud Server Backup Servic