首页 > 解决方案 > 使用以前正在运行的活动而不是开始新的活动

问题描述

是否可以在不影响后台堆栈的情况下使用以前正在运行的活动而不是开始一个新活动?

例如活动 A -> B -> C -> A 我想实现系统将使用活动 A 实例而不启动一个新的实例,并且不影响返回堆栈。

因此,当用户单击返回时,他将沿着原始路径行进,最后一个活动将是 A 而不是 B,只需使用 singleTop/ReorderToFront 标志,我将能够使用原始活动,但我将丢失返回堆栈

我希望获得“浏览器般的体验”,因此每次用户单击返回时,他都会返回到他的上一页,例如,情况可能要复杂得多

A -> B -> C -> A -> B -> B -> C -> D -> A 等等...

标签: androidandroid-activity

解决方案


如果您想模拟浏览器的行为,那么您应该只允许 Android 创建新的活动实例,它会这样做。然后,用户可以按 BACK 以导航回活动列表。

您不能重用现有实例并重新排列它们并仍然维护后退堆栈,因为当 Android 将 Activity 从堆栈中的任何位置移动到前面时(您可以使用FLAG_ACTIVITY_REORDER_TO_FRONT),它会将其从后堆栈中的位置移除.

如果您真的想重用现有实例并维护后台堆栈,那么您必须自己实现:

创建一个static ArrayList<Class> stack用作堆栈的变量,以记住Activity在导航中的哪个位置使用了哪个变量。每次你启动一个Activity你应该我们startActivity()并确保你设置FLAG_ACTIVITY_REORDER_TO_FRONT了一个现有的实例将被移动到前面。当您调用startActivity() you must also push theClass instance of theActivity` 到您的堆栈上时。这使您可以跟踪以什么顺序启动的活动。这一切都很好。现在,当用户按下 BACK 时,棘手的部分就来了。

onBackPressed()每个Activity. 当onBackPressed()被调用时,执行以下操作:

// pop my Activity off the stack
Class myClass = stack.remove(stack.size() - 1);
// Check if there are any more instances of my Activity in the stack
//  Don't finish this instance if the instance exists in the stack
if (!stack.contains(myClass)) {
    // There are no more instances of my Activity in the stack, so
    //   finish this instance
    finish();
    // Check if this is the root Activity, if so we are done!
    if (stack.size() == 0) {
        return;
    }
}
// Get the Class representing the previous Activity from the top of the stack
Class activityClass = stack.get(stack.size() - 1);
// Launch that Activity
Intent launchIntent = new Intent(this, activityClass);
launchIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(launchIntent);

这会将当前Activity从堆栈中弹出,Activity如果堆栈中没有它的更多实例,则完成,Activity从堆栈顶部获取前一个并将其启动并将其带到前面。这给出了您正在寻找的错觉。


推荐阅读