Android 应用崩溃后重启的机制

一、出现的场景

  在开发过程中,想必你也一定遇到过这样的问题,当我们的应用发生Crash时异常退出,然后又自动启动跳转到未知页面,此时应用在崩溃前保存的全局变量被重置,用户状态丢失,显示数据错乱。更让我们头疼的是,这种崩溃后重启的情况,并不是每次都会遇到,那么究竟是因为什么呢?

  经测试,在 Android 的 API 21 ( Android 5.0 ) 以下,Crash 会直接退出应用,但是在 API 21 ( Android 5.0 ) 以上,系统会遵循以下原则进行重启:

  1. 包含 Service,如果应用 Crash 的时候,运行着Service,那么系统会重新启动 Service。
  2. 不包含 Service,只有一个 Activity,那么系统不会重新启动该 Activity。
  3. 不包含 Service,但当前堆栈中存在两个 Activity:Act1 -> Act2,如果 Act2 发生了 Crash ,那么系统会重启 Act1。
  4. 不包含 Service,但是当前堆栈中存在三个 Activity:Act1 -> Act2 -> Act3,如果 Act3 崩溃,那么系统会重启 Act2,并且 Act1 依然存在,即可以从重启的 Act2 回到 Act1。

看了上述解释,我们终于知道应用在什么种情况下才会重启。

二、解决方法

   维护所有已经打开的Activity到一个List中,崩溃时在Thread.UncaughtExceptionHandler 中finish掉所有Activity, 这样按上述列举的规则系统就不会自动重启相应的Activity了。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要捕获 Android 应用程序的异常并重启应用程序,可以使用 Thread.UncaughtExceptionHandler 接口。该接口用于捕获未捕获的异常,并在捕获异常后重启应用程序。 下面是一个简单的示例代码,用于设置应用程序的 UncaughtExceptionHandler: ``` public class MyApplication extends Application implements Thread.UncaughtExceptionHandler { @Override public void onCreate() { super.onCreate(); Thread.setDefaultUncaughtExceptionHandler(this); } @Override public void uncaughtException(Thread thread, Throwable ex) { // 捕获异常并重启应用程序 Intent intent = new Intent(getApplicationContext(), MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(getBaseContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT); AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 1000, pendingIntent); System.exit(2); } } ``` 在上述示例代码中,我们创建了一个自定义的 Application 类,并实现 Thread.UncaughtExceptionHandler 接口。在 onCreate() 方法中,我们将当前线程的默认 UncaughtExceptionHandler 设置为该应用程序的 UncaughtExceptionHandler。 当应用程序中有未捕获的异常时,会调用 uncaughtException() 方法。在该方法中,我们创建一个 Intent 对象,用于启动 MainActivity,然后使用 PendingIntent 将该 Intent 对象封装为一个闹钟事件,并在 1 秒钟后启动该事件。最后,我们调用 System.exit() 方法退出应用程序。 这样,当应用程序中发生未捕获的异常时,应用程序将自动重启
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值