【发布时间】:2017-05-30 05:51:12
【问题描述】:
我正在使用 Thread.setDefaultExceptionHandler() 尝试启动一个新活动,从而有效地重新启动应用程序。但是,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 会显示之前的应用。
日志文件包含以下内容(注意 pid 略有不同):
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 如此迫切地想要终止刚刚启动的进程?
【问题讨论】:
-
你试过使用android.os.Process.killProcess吗?
-
我不这么认为,但已经有一段时间了。这目前不在我的优先级列表中,因此在我尝试其他任何事情之前将需要“一段时间”。谢谢。
-
不要使用 System.exit (1),因为它不会清理任务堆栈,也不会让操作系统有机会干净地退出您的应用程序。在此处阅读有关任务堆栈的更多信息:developer.android.com/guide/components/activities/…
标签: android android-activity uncaught-exception