android - 使用以前正在运行的活动而不是开始新的活动
问题描述
是否可以在不影响后台堆栈的情况下使用以前正在运行的活动而不是开始一个新活动?
例如活动 A -> B -> C -> A 我想实现系统将使用活动 A 实例而不启动一个新的实例,并且不影响返回堆栈。
因此,当用户单击返回时,他将沿着原始路径行进,最后一个活动将是 A 而不是 B,只需使用 singleTop/ReorderToFront 标志,我将能够使用原始活动,但我将丢失返回堆栈
我希望获得“浏览器般的体验”,因此每次用户单击返回时,他都会返回到他的上一页,例如,情况可能要复杂得多
A -> B -> C -> A -> B -> B -> C -> D -> A 等等...
解决方案
如果您想模拟浏览器的行为,那么您应该只允许 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
从堆栈顶部获取前一个并将其启动并将其带到前面。这给出了您正在寻找的错觉。
推荐阅读
- c - 父子之间的通信 dup()
- owl - 如何比较 swrl 中的日期时间持续时间?
- c# - 如何序列化嵌套在类中的实例列表?
- swift - 如何使用 NSOpenPanel 导入视频文件?
- regex - 使用捕获组匹配重复 [01] 的正则表达式
- node.js - 如何从快递发送默认的nextjs 404 not found错误页面?
- python - 如何自定义 fairseq 模型输入?
- tensorflow - 我们如何将 keras 模型 .h5 文件转换为 tensorflow 保存的模型 (.pb)
- javascript - 如何解决“尝试从 json 文件中获取 url 时我未定义”?
- visual-studio - MSBuild 以最新的 TargetPlatformVersion 为目标