按HOME后重新启动应用程序时如何返回最新启动的活动?

sol*_*ole 23 stack android task android-activity

熟悉的场景:我有一个Main活动,在按下按钮时启动游戏活动.如果用户按下HOME,然后再次启动我的应用程序,则应该显示Game活动,这是他在使用应用程序时最后所做的事情.

但是,相反的是他再次获得Main活动.我觉得Android正在创建另一个 MainActivity实例并将其添加到该应用程序的堆栈中,而不是仅仅选择顶部的任何内容,因为如果我在重新启动应用程序后按BACK,我会进入游戏活动!并且每次调用Main.onCreate方法,而不是调用GameActivity.onResume.

AndroidManifest.xml几乎是'骨头':

<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>
Run Code Online (Sandbox Code Playgroud)

如你所见,没有什么太花哨的.

这就是新活动的推出方式,也非常简单:

Intent intent = new Intent(this, GameActivity.class);
startActivity(intent);
Run Code Online (Sandbox Code Playgroud)

从理论上说,这应该在Android中起到"开箱即用"的作用,因为一个非常相似的问题的答案是:在Android中维护标准应用程序活动后备堆栈状态(使用singleTask启动模式),但事实并非如此.

我一直在阅读和重读有关活动和任务和堆栈的文档,并在SO中浏览所有相关的答案,但我不明白为什么这么简单的设置不能按预期工作.

Sac*_*ani 28

    @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... 
} 
Run Code Online (Sandbox Code Playgroud)


sol*_*ole 18

哦,我想我找到了答案.

因为我是使用IntelliJ启动应用程序,所以它似乎以不同于用户的方式启动应用程序,单击主屏幕小部件,将启动.在另一个SO问题的答案中解释了这一点:

这是因为用于启动应用程序的意图不同.Eclipse使用没有操作且没有类别的intent启动应用程序.Launcher使用android.intent.action.MAIN动作和android.intent.category.LAUNCHER类别的intent启动应用程序.安装程序使用android.intent.action.MAIN操作启动应用程序,没有类别.

参考:应用程序始终从根活动开始新鲜而不是恢复背景状态(已知错误)

所以我手动杀死了手机中的应用程序,并从主屏幕小部件再次重新启动它.然后打开GameActivity,按下HOME.现在,重新启动时,GameActivity仍然可见并保持其状态,就像我离开时一样.

我猜想之前按下快捷键时创建活动的新实例的原因是由于使用了不同的Intent来启动活动.