Android(安卓)应用Crash 后自动重启
16lz
2021-12-04
前提
首先,我们肯定要在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里面,把应用在自己的进程里面的启动起来。
更多相关文章
- Android(安卓)内存笔记
- 2013.08.21——— android 四种启动模式
- Android跨进程通信
- android流量统计
- Android学习笔记之mainfest文件中android属性
- Android解决禁止使用http协议的方案
- 活动的启动模式汇总
- Android(安卓)系统启动过程
- Android学习笔记之mainfest文件中android属性
随机推荐
- 云关系型数据库(Relational Database Serv
- 云数据迁移(Cloud Data Migration,CDM)
- 弹性云服务器(Elastic Cloud Server,ECS)
- 云专线(Direct Connect,DC)
- 内容分发网络(Content Delivery Network,CD
- 虚拟私有云(Virtual Private Cloud,VPC)
- SpringMVC @Value注解无法获取值 报Illeg
- 弹性公网IP(Elastic IP,EIP)
- 弹性负载均衡(Elastic Load Balance,ELB)
- 云服务器备份(Cloud Server Backup Servic