使用以前的跑步活动而不是开始新的活动

时间:2018-09-20 12:15:38

标签: android android-activity

是否可以使用以前运行的活动而不是开始新的活动而不影响后退堆栈?

例如活动A-> B-> C-> A 我想实现系统将在不启动新活动的情况下使用活动A实例,而又不影响后退堆栈。

因此,当用户单击“上一步”时,他将走过原始路径,最后一个活动将是A而不是B,只需使用singleTop / ReorderToFront标志,我就可以使用原始活动,但我会丢失后退堆栈

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

复杂得多。

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

1 个答案:

答案 0 :(得分:0)

如果您想模拟浏览器的行为,则应该只允许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 the Class instance of the Activity`到堆栈中时。这使您可以跟踪以什么顺序启动了哪些活动。今后一切正常。现在,当用户按下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并启动它,将其带到前面。这给出了您要寻找的错觉。