熟悉的场景:我有一个 Main Activity ,当按下按钮时它会启动一个 Game Activity 。如果用户按下 HOME,然后再次启动我的应用程序,它应该会显示 Game Activity ,这是他在使用应用程序时最后做的事情。
然而,发生的事情是他再次获得了 Main Activity 。我感觉 Android 正在创建 MainActivity 的 another 实例并将其添加到该应用程序的堆栈中,而不是仅仅选择顶部的任何内容,因为如果我在重新启动应用程序后按 BACK,我进入游戏 Activity !并且每次调用Main.onCreate方法,而不是调用GameActivity.onResume。
我的 AndroidManifest.xml
几乎是“ Backbone ”:
<activity android:name="MainActivity" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="GameActivity" android:label="@string/app_name">
</activity>
如您所见,没有什么太花哨的。
这就是新 Activity 的启动方式,也很简单:
Intent intent = new Intent(this, GameActivity.class);
startActivity(intent);
理论上,这应该在 Android 中“开箱即用”,正如对一个非常相似的问题的回答所说:Maintaining standard application Activity back stack state in Android (using singleTask launch mode) ,但事实并非如此。
我一直在阅读和重新阅读有关 Activity 和 Task 和 Stacks 的文档,并浏览了 SO 中的所有相关答案,但我不明白为什么这么简单的设置不能按预期工作。
最佳答案
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
// Activity was brought to front and not created,
// Thus finishing this will get us to the last viewed activity
finish();
return;
}
// Regular activity creation code...
}
关于android - 按HOME后重新启动应用程序时如何返回最新启动的 Activity ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6337217/