你如何使用Intent.FLAG_ACTIVITY_CLEAR_TOP清除活动栈?如何使用、Intent、FLAG_ACTIVITY_CLEAR_TOP

2023-09-12 00:11:28 作者:原谅至无可转寰.

我已经通过关于使用这个几个职位读,但必须缺少的东西,因为它不是为我工作。我的活性的清单中有launchmode =singleTop。它开始活动B,用launchmode =singleInstance。活性B打开一个浏览器,并接收和意图背面,这就是为什么它的singleInstance。我想覆盖后退按钮以便用户发送回的活动时,然后可以preSS回到离开活动,而不是回到b活动了。

I've read through several posts about using this, but must be missing something as it's not working for me. My activity A has launchmode="singleTop" in the manifest. It starts activity B, with launchmode="singleInstance". Activity B opens a browser and receives and intent back, which is why it's singleInstance. I'm trying to override the back button so that the user is sent back to the activity A, and can then press Back to leave the activity, rather than back to activity B again.

// activity B
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
 if (android.os.Build.VERSION.SDK_INT < android.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

After returning from the browser, the stack is... A,B,Browser,B

我希望这code要更改栈... 一个 ......使pressing回一次将用户返回到主屏幕。

I expect this code to change the stack to... A ... so that pressing back once more takes the user back to the Home Screen.

相反,它似乎改变堆栈为... A,B,浏览器,B,A ......好像这些标志是不存在的。

Instead it seems to change the stack to... A,B,Browser,B,A ...as though those flags aren't there.

我试过startActivity后调用完成()在活动B,但随后的后退按钮把我带回到浏览器了!

I tried calling finish() in activity B after startActivity, but then the back button takes me back to the browser again!

我在想什么?谢谢!

推荐答案

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

@bitestar has the correct solution, but there is one more step:

这是隐藏在文档,但您必须修改 launchMode 活动的任何东西比其他标准。否则,将删除和重建,而不是被重置顶端。

It was hidden away in the docs, however you must change the launchMode of the Activity to anything other than standard. Otherwise it will be destroyed and recreated instead of being reset to the top.