清除整个历史堆栈并在 Android 上启动一个新活动 [英] Clear the entire history stack and start a new activity on Android
问题描述
是否可以在堆栈上启动一个活动,在它之前清除整个历史记录?
Is it possible to start an activity on the stack, clearing the entire history before it?
情况
我有一个活动堆栈,可以是 A->B->C 或 B->C(屏幕 A 选择用户令牌,但许多用户只有一个令牌).
I have an activity stack that either goes A->B->C or B->C (screen A selects the users token, but many users only have a single token).
在屏幕 C 中,用户可能采取使屏幕 B 无效的操作,因此应用程序希望将它们带到屏幕 A,无论它是否已经在堆栈中.屏幕 A 应该是我的应用程序中堆栈中唯一的项目.
In screen C the user may take an action which makes screen B invalid, so the application wants to take them to screen A, regardless of whether it is already in the stack. Screen A should then be the only item on the stack in my application.
注意事项
还有许多其他类似的问题,但我没有找到任何可以回答这个确切问题的内容.我尝试调用 getParent().finish()
- 这总是导致空指针异常.FLAG_ACTIVITY_CLEAR_TOP
仅当活动已经在堆栈中时才有效.
There are many other similar questions, but I haven't found anything that answers this exact question. I tried calling getParent().finish()
- this always results in a null pointer exception. FLAG_ACTIVITY_CLEAR_TOP
only works if the activity is already on the stack.
推荐答案
在 API 级别 11 中,专门为此添加了一个新的 Intent 标志:Intent.FLAG_ACTIVITY_CLEAR_TASK
In API level 11 a new Intent Flag was added just for this: Intent.FLAG_ACTIVITY_CLEAR_TASK
只是为了澄清,使用这个:
Just to clarify, use this:
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
科特林
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
不幸的是,对于 API lvl <= 10,我还没有找到一个干净的解决方案.DontHackAndroidLikeThis";解决方案确实是纯粹的hackery.你不应该那样做.:)
Unfortunately for API lvl <= 10, I haven't yet found a clean solution to this. The "DontHackAndroidLikeThis" solution is indeed pure hackery. You should not do that. :)
根据@Ben Pearson 的评论,对于 API <=10 现在可以使用 IntentCompat 类相同.可以使用 IntentCompat.FLAG_ACTIVITY_CLEAR_TASK
标志来清除任务.因此,您也可以支持 API 级别 11 之前的版本.
As per @Ben Pearson's comment, for API <=10 now one can use IntentCompat class for the same. One can use IntentCompat.FLAG_ACTIVITY_CLEAR_TASK
flag to clear task. So you can support pre API level 11 as well.
这篇关于清除整个历史堆栈并在 Android 上启动一个新活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!