在 Android uncaughtException 之后,ActivityManager 会强制停止新进程

after Android uncaughtException, ActivityManager does force stop on new process

我正在使用 Thread.setDefaultExceptionHandler() 尝试启动一个新的 activity,有效地重新启动应用程序。但是,似乎 ActivityManager 正在启动新的应用程序进程。

我已经尝试了很多实验。最成功的是这段代码,在异常处理程序中:

public void handleUncaughtException (Thread thread, Throwable e)
{
  Intent intent = new Intent (getBaseContext (), RestartActivity.class);
  intent.addFlags (Intent.FLAG_ACTIVITY_CLEAR_TOP |
                   Intent.FLAG_ACTIVITY_CLEAR_TASK |
                   Intent.FLAG_ACTIVITY_NEW_TASK);

  PendingIntent pending =
    PendingIntent.getActivity (getBaseContext (), 0, intent, PendingIntent.FLAG_ONE_SHOT);

  try {
    pending.send ();
  }
  catch (PendingIntent.CanceledException e1) {
    logE ("send pending intent:" + e1); // logE is a wrapper for Log.e().
  }

  System.exit (1);
}

在这种情况下,RestartActivity 启动并显示,但只有一秒钟。然后该应用程序完全消失,Android 显示之前的应用程序。

日志文件包含这个(注意 pids 略有不同):

05-29 22:46:28.429 1465-3665/? I/ActivityManager: Force stopping com.perinote.crashtest appid=10170 user=0: from pid 14484
05-29 22:46:28.429 1465-3665/? I/ActivityManager: Killing 14486:com.perinote.crashtest/u0a170 (adj 0): stop com.perinote.crashtest

我也试过使用 AlarmManager,在这个变体中:

public void handleUncaughtException (Thread thread, Throwable e)
{
  Intent intent = new Intent (getBaseContext (), RestartActivity.class);
  intent.addFlags (Intent.FLAG_ACTIVITY_CLEAR_TOP |
                   Intent.FLAG_ACTIVITY_CLEAR_TASK |
                   Intent.FLAG_ACTIVITY_NEW_TASK);

  PendingIntent pending =
    PendingIntent.getActivity (getBaseContext (), 0, intent, PendingIntent.FLAG_ONE_SHOT);

  AlarmManager alarm = (AlarmManager)getSystemService (Context.ALARM_SERVICE);
   alarm.set (AlarmManager.RTC, System.currentTimeMillis () + 3000, pending);

  System.exit (1);
}

在这种情况下,RestartActivity 根本不显示,我在 logcat 中看到这样一行:

05-29 22:06:46.841 1465-11842/? I/ActivityManager: Force stopping com.perinote.crashtest appid=10170 user=0: from pid 12551

是什么导致 Android 非常想终止刚刚启动的进程?

由于我误会了您的意图,因此进行了大量编辑。

第一个版本不起作用,因为您正在向您自己的应用程序发送待定意图。仅仅因为它是一个未决的意图并不意味着它会在一个新的进程中 运行 ,这意味着无论其他应用程序调用它(例如通知的启动器)它都会被激活,就像你自己的进程启动了意图。例如,它可以访问私人活动。它实际上是在你被杀死之前在你的进程中开始的,然后它和你一起被杀死。

警报管理器根本不起作用,因为其中的未决意图必须是针对 BroadcastReceiver - 它不接受服务或 Activity。如果您在清单中放置一个接收器并对其使用待定意图,您可能可以让它工作。