同时关闭几个android活动

前端之家收集整理的这篇文章主要介绍了同时关闭几个android活动前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在我的应用程序中,您可以浏览多个活动,直到活动堆栈非常深.

我们希望每个Activity上都有一个按钮,它会直接返回主菜单 – 即除了第一个活动之外,从堆栈中弹出所有活动.

我把按钮放在一个View中,我可以很容易地把它放在应用程序中的每个Activity上,但我无法弄清楚如何一举关闭几个Activity.

(如果可能的话,如果View可以计算出自己关闭多少个活动就好了 – 也就是检测它自己的Activity有多深.)

解决方法

看看意图标志FLAG_ACTIVITY_CLEAR_TOP,它表示它将目标活动带到堆栈顶部,删除其上可能已经存在的所有其他内容.因此,使用您可以添加到所有活动的按钮来启动针对主菜单的意图,并设置该标志.

从文档:

If set,and the activity being
launched is already running in the
current task,then instead of
launching a new instance of that
activity,all of the other activities
on top of it will be closed and this
Intent will be delivered to the (now
on top) old activity as a new Intent.

For example,consider a task
consisting of the activities: A,B,C,
D. If D calls startActivity() with an
Intent that resolves to the component
of activity B,then C and D will be
finished and B receive the given
Intent,resulting in the stack now
being: A,B.

The currently running instance of
activity B in the above example will
either receive the new intent you are
starting here in its onNewIntent()
method,or be itself finished and
restarted with the new intent. If it
has declared its launch mode to be
“multiple” (the default) and you have
not set FLAG_ACTIVITY_SINGLE_TOP in
the same intent,then it will be
finished and re-created; for all other
launch modes or if
FLAG_ACTIVITY_SINGLE_TOP is set then
this Intent will be delivered to the
current instance’s onNewIntent().

This launch mode can also be used to good effect in conjunction with FLAG_ACTIVITY_NEW_TASK: if used to start the root activity of a task,it will bring any currently running instance of that task to the foreground,and then clear it to its root state. This is especially useful,for example,when launching an activity from the notification manager.

原文链接:https://www.f2er.com/android/317388.html

猜你在找的Android相关文章