为什么FLAG_ACTIVITY_CLEAR_TOP不起作用? [英] Why does FLAG_ACTIVITY_CLEAR_TOP not work?

查看:564
本文介绍了为什么FLAG_ACTIVITY_CLEAR_TOP不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所述,为什么intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)无法使用?

As the title says, Why intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) or intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) won't work?

我有3个活动,让我们说A,B和C.

I have 3 Activities let us say A, B and C.

当我尝试使用代码从C启动活动A时:

When I am trying to launch Activity A from C with code:

Intent i = new Intent(this, A.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);

它只是启动活动A,但没有清除顶部. -_-

It simply starts Activity A but doesn't clear the top.! -_-

我也尝试过使用setFlags().

关于此问题,我在SO上阅读了不同的问题,但找不到正确的答案. > _<

I read different questions on SO about this problem, but I couldn't find the right answer. >_<

请有人帮忙!

修改

@codeMagic要求的活动"A"中onBackPressed()的代码.

Code for onBackPressed() in activity 'A' as requested by @codeMagic.

@Override
public void onBackPressed(){
    if(wvLogin.canGoBack())
        wvLogin.goBack();
    else
        super.onBackPressed();
}

推荐答案

摘自 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.

正如您在注释中添加的那样,活动A在调用B之前已经完成,因此这种情况不适用.相反,将启动活动A的新实例.

As you added in your comment, the activity A has been finished before calling B, so this situation doesn't apply. A new instance of activity A will be launched instead.

如我所见,您在这里有两个选择:

As I see it, you have two options here:

1)使用Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK标志.这将启动活动A作为堆栈的根.它可以工作,但是堆栈中的所有其他活动都将丢失.假设A是第一个活动(或至少您对任务堆栈中的任何先前活动不感兴趣),那么这无关紧要. 注意:CLEAR_TASK要求API级别11.

1) Use the Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK flags. This will start activity A as the root of the stack. It works, but any other activities in the stack will be lost. Assuming A was the first activity (or at least, that you are not interested in any previous activities in the task stack) then it doesn't matter. Note: CLEAR_TASK requires API Level 11.

2)另一个可能的解决方案(如果先前的假设不成立的话)将是根本不使用意图标志:

2) Another possible solution (in case the previous assumption is not true) would be to not use intent flags at all:

  • B以startActivityForResult()开头C.
  • C没有完成调用A的工作,而是为B设置了一个结果,指示必须启动A.
  • B.afterActivityResult()中,完成B并启动A.
  • B starts C with startActivityForResult().
  • Instead of calling A, C finishes, having set a result for B indicating that A must be launched.
  • In B.afterActivityResult(), finish B and launch A.

这篇关于为什么FLAG_ACTIVITY_CLEAR_TOP不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆