如何限制Android应用程序堆栈中同一活动的数量?[英] How to limit the number of the same Activity on the stack for an Android application

本文是小编为大家收集整理的关于如何限制Android应用程序堆栈中同一活动的数量?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

这可以在 Android 应用中实现吗?我想让它无论用户启动多少次 activityA,当他们点击后退按钮时,他们永远不会得到超过一次的 activityA.

我在当前代码中发现我只有两个选择:1.我可以在activityA中调用finish(),这将阻止它完全通过后退按钮访问,或者2.我不调用finish(),然后如果用户在使用过程中启动activityA(n)次,点击后退按钮时会有(n)次.

同样,我想通过点击后退按钮来访问 activityA,但没有理由在堆栈上保留同一活动的多个实例.有没有办法将队列中某个活动的实例数限制为仅 1 个?

推荐答案

一个选项是每次启动 Activity 时都使用 Intent.FLAG_ACTIVITY_REORDER_TO_FRONT,这样如果实例存在,它就会被带到堆栈的前面,而不是每次都创建时间.这样您就可以确保只有一个 Activity 会留在堆栈中.

其他推荐答案

您可能希望将您的 Activity 设置为 singleTop -- 这基本上意味着您可以有多个实例,但是如果您尝试在自身之上启动一个实例.请参阅有关活动和任务的 Android 文档.

本文地址:https://www.itbaoku.cn/post/102495.html

问题描述

Is this possible in an Android app? I want to make it so that no matter how many times a user starts activityA, when they hit the back button they will never get more than one occurence of activityA.

What I am finding in my current code is that I have only two options: 1. I can call finish() in activityA which will prevent it from being accessible via the back button completely, or 2. I do not call finish(), and then if the user starts activityA (n) times during their usage, there will be (n) instances when hitting the back button.

Again, I want to have activityA accessible by hitting the back button, but there is no reason to keep multiple instances of the same activity on the stack. Is there a way to limit the number of instances of an activity in the queue to only 1?

推荐答案

One option is to use Intent.FLAG_ACTIVITY_REORDER_TO_FRONT every time you launch an Activity so that if an instance exists it is brought to the front of the stack and not created every time. This way you are ensured that only one Activity will remain on stack.

其他推荐答案

You might want to set your activity as singleTop -- this basically means that you can have multiple instances, but the app will reuse an instance if you try to launch an instance on top of itself. See the Android documentation on Activities and Tasks.