Activity 在后台按下主页按钮时被杀死

Activity in background gets killed when Home button is pressed

我遇到了奇怪的问题,假设我有两个活动 A 和 B,应用程序以 Activity A 开始,我继续 activity B 按 Android 主页按钮,return 到应用程序,这让我回到 Activity B。然后我按下返回按钮(工具栏上的硬件),这将关闭应用程序,但它应该 return 我到 Activity A . Activity B 没有覆盖 onBackPressed 并且 Activity A 在清单中声明为 PARENT_ACTIVITY。我从没有标志的 Intent 开始。知道为什么会这样吗?谢谢

在你的 activity A 中调用你的 activity B 时,也许你有以下命令:

finish();

如果是,则应删除此行。然后,当您从 activity B 按下后退键时,您应该 return A。 如果没有,也许可以尝试分享您的代码。

后退按钮的行为取决于系统版本。支持在旧 Android 版本中提供后退导航,如下所述:

https://developer.android.com/training/implementing-navigation/ancestral.html

<application ... >
    ...
    <!-- The main/home activity (it has no parent activity) -->
    <activity
        android:name="com.example.myfirstapp.MainActivity" ...>
        ...
    </activity>
    <!-- A child of the main activity -->
    <activity
        android:name="com.example.myfirstapp.DisplayMessageActivity"
        android:label="@string/title_activity_display_message"
        android:parentActivityName="com.example.myfirstapp.MainActivity" >
        <!-- Parent activity meta-data to support 4.0 and lower -->
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.myfirstapp.MainActivity" />
    </activity>
</application>

调试返回堆栈问题的最佳和最方便的方法是在开发人员选项中启用“不保留活动”选项。

这是我最好的猜测。祝你好运!

为了 运行 一个新的 activity 而不破坏旧的,你必须将标志 FLAG_ACTIVITY_NEW_TASK 添加到将 运行 activity:

 Intent intent = new Intent(MainActivity.this, MainActivity2.class);
 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 startActivity(intent);

设置此标志时:

this activity will become the start of a new task on this history stack. A task (from the activity that started it to the next task activity) defines an atomic group of activities that the user can move to. Tasks can be moved to the foreground and background; all of the activities inside of a particular task always remain in the same order.

所以启动它的activity会留在栈中,因此你可以再次调用它,因此它也可以在按下BACK_BUTTON时自动再次调用 即使您之前按了 HOME_BUTTON


并且您必须将@gduh 的答案与我的结合起来,因为您必须确保在调用 ActivityB 时没有在 ActivityA 中调用 finish();

感谢您的帮助,问题是由清单 android:launchMode=singleinstance 中 activity 的这个标志引起的(它最初不是我的项目,所以我错过了,我只是希望我没有搞砸什么否则通过删除它)