Mic*_*evy 6 android android-activity
我的应用程序运行在运行Android Gingerbread 2.3.7的自定义版本的特殊设备上
在某些情况下系统将终止我的应用程序.我假设设备制造商考虑这些紧急情况,应立即关闭所有第三方应用程序,以便设备可以完成其主要任务.
我可以使用模拟器复制我在设备上看到的行为,并在DDMS中选择我的任务并单击"停止进程"按钮.这是我看到的行为.
我的应用程序通常会执行四个活动,活动A启动活动B,B启动活动C,C启动活动D.因此,当活动D在顶部运行时,我的堆栈是:
A B C D
如果此时进程终止,则活动D不会接收onPause()或onStop()调用.它没有机会拯救其国家.
在该过程停止后,Android的ActivityManager为我的应用程序启动一个新任务并启动Activity C.我认为这是重新启动崩溃的应用程序的标准Android行为.
我的问题是我能控制这种重启行为吗?如果Android要重新启动我的应用程序,我需要恢复活动堆栈,活动C没有意义独立运行(单击后退按钮将退出应用程序,这对此活动没有意义).
我可以阻止重启吗?我可以按顺序重新启动所有活动吗?我可以重新启动只是启动活动A吗?
我确实发现了这个有趣的讨论,我相信这解释了为什么重新启动Activity C而不是Activity D.
在重新启动活动时 - 如果运行前台活动的进程消失,如果系统没有有效的保存状态,系统将丢弃该活动(通常意味着它已暂停并且已将系统提供给系统暂停之前的onSaveInstanceState的结果).一旦决定是否抛弃该活动,它将恢复现在位于堆栈顶部的任何活动.如果这是你的一项活动 - 或者是因为你有一个在崩溃的那个后面,或者一个崩溃的那个在某种程度上它是稳定的暂停状态 - 那么它将再次开始你的过程以显示最高活动.
还有一些类似的问题,如防止活动堆栈被恢复?这个有趣的主题
经过大量实验,我选择了“Android Developers \xe2\x80\xba”中暗示的方法 Activity restart crash after OS Kills it ”中暗示的方法。有一次问答交流:
\n\n问题:
\n\n\n\n\n“已单步执行代码并了解您正在讨论的内容。它调用 onSaveInstanceState 并将数据保存在 Bundle 中。操作系统终止进程后,当 Activity 重新启动时,此 Bundle 信息是否可用?”
\n
回答:
\n\n\n\n\n“应该是这样。您将在 onCreate() 和 onRestoreInstanceState() 中获得该 Bundle。如果没有要恢复的 Bundle,则可以为 onCreate() 传递 null。onRestoreInstanceState() 是\n 仅当有要恢复的捆绑包时才调用。”
\n
我将应用程序被终止后恢复所需的所有会话数据移至可序列化的单例中。
\n\n在 onSaveInstanceState() 中,我将序列化的会话数据放入 savingInstanceState 包中
\n\n@Override\npublic void onSaveInstanceState(Bundle savedInstanceState) {\n super.onSaveInstanceState(savedInstanceState);\n // save and restore session data to instance state to recover from task termination \n savedInstanceState.putSerializable(SessionVariables.class.getName(), mSessionVariables); \n}\nRun Code Online (Sandbox Code Playgroud)\n\n在 onCreate() 和 onRestoreInstanceState() 中,我测试我的会话单例实例是否有效。如果它没有有效数据,我会从 savingInstanceState 包中恢复会话变量,并将此恢复的对象作为我的会话变量单例。
\n\n@Override\npublic void onRestoreInstanceState(Bundle savedInstanceState) {\n super.onRestoreInstanceState(savedInstanceState);\n\n if (mSessionVariables.propertyThatShouldbeGood == null || mSessionVariables.propertyThatShouldbeGood .length() == 0)\n {\n // save and restore session data to instance state to recover from task termination\n Serializable serializedSessionVariables = savedInstanceState.getSerializable(SessionVariables.class.getName());\n\n if (serializedSessionVariables != null) {\n mSessionVariables = (SessionVariables) serializedSessionVariables;\n SessionVariables.putInstance(mSessionVariables);\n }\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n现在,当我的任务被终止时,Android 会从堆栈中恢复之前的活动。onCreate() 从保存的实例状态包中恢复所有必要的会话数据。
\n\n此时“后退”按钮也可以正常工作,所以我错了,Android 没有保留 Activity 堆栈。我认为它只是根据需要恢复背部活动(当您向后导航时)。如果您不返回,则不会创建它们。至少在 HierarchyViewer 中是这样的。
\n\n当我的堆栈为 ABCD 并且任务被终止时,活动“C”恢复,“D”丢失。但是,现在“C”处于健康状态,用户可以轻松导航回“D”。现在,我也可以从“C”自动启动“D”活动,我只是还没有时间。
\n