有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用Intent。标记\u活动\u清除\u顶部以清除活动堆栈?

我已经读了好几篇关于使用这个的帖子,但肯定遗漏了一些东西,因为它对我不起作用。我的活动A在清单中有launchmode=“singleTop”。它使用launchmode=“singleInstance”启动活动B。活动B打开浏览器并接收和返回意图,这就是为什么它是单实例。我试图覆盖“后退”按钮,以便将用户发送回活动A,然后按“后退”离开活动,而不是再次返回活动B

// activity B
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
 if (安卓.os.Build.VERSION.SDK_INT < 安卓.os.Build.VERSION_CODES.ECLAIR
  && keyCode == KeyEvent.KEYCODE_BACK
  && event.getRepeatCount() == 0) onBackPressed();
 return super.onKeyDown(keyCode, event);
}
@Override
public void onBackPressed() {
 startActivity(new Intent(this, UI.class)
 .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK));
 return;
}

从浏览器返回后,堆栈将。。。 A、 B,浏览器,B

我希望此代码将堆栈更改为。。。 A. ... 因此,再次按下back键会将用户带回主屏幕

相反,它似乎将堆栈更改为。。。 A、 B,浏览器,B,A ...好像那些旗帜不在那里

在startActivity之后,我尝试在活动B中调用finish(),但是“上一步”按钮再次将我带回浏览器

我错过了什么


共 (6) 个答案

  1. # 1 楼答案

    虽然这个问题已经有了足够的答案,但我想有人会想知道为什么这面旗帜会以这种特殊的方式工作,这就是我在Android documentation中发现的

    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().


    所以,要么,
    1。将活动A的launchMode更改为标准的其他内容(即singleTask或其他内容)。那么您的标志FLAG_ACTIVITY_CLEAR_TOP将不会重新启动活动A

    或者

    2。使用Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP作为您的标志。然后它会按照你的愿望工作

  2. # 2 楼答案

    我使用三个标志来解决问题:

    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|
                    Intent.FLAG_ACTIVITY_CLEAR_TASK | 
                    Intent.FLAG_ACTIVITY_NEW_TASK);
    
  3. # 3 楼答案

    在清单文件中添加android:noHistory=“true”

    <manifest >
            <activity
                android:name="UI"
                android:noHistory="true"/>
    
    </manifest>
    
  4. # 4 楼答案

    @bitestar有正确的解决方案,但还有一步:

    它隐藏在文档中,但是您必须将ActivitylaunchMode更改为standard以外的任何内容。否则它将被销毁并重新创建,而不是重置为顶部

  5. # 5 楼答案

    我已开始活动A->;B->;C->;D 当按下活动D上的后退按钮时,我想转到活动A。因为A是我的起点,因此已经在堆栈上,A顶部的所有活动都被清除,您不能从A返回到任何其他活动

    这实际上在我的代码中起作用:

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent a = new Intent(this,A.class);
            a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(a);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }       
    
  6. # 6 楼答案

    为此,我使用FLAG_ACTIVITY_CLEAR_TOP标志来启动Intent
    (不带FLAG_ACTIVITY_NEW_TASK

    launchMode = "singleTask"在已启动活动的清单中

    似乎它可以根据我的需要工作——活动不会重新启动,所有其他活动都已关闭