简体   繁体   English

如何销毁一个活动,使其在按下后退按钮时不显示?

[英]How to destroy an Activity so it doesn't show up when the back button is pressed?

I have two Activities, A and B. Here is a normal scenario: A is running, then sends an intent to B. A is paused, and B displays. 我有两个活动,A和B。这是一个正常的情况:A正在运行,然后向B发送一个意图。A被暂停,并且B显示。 When the user presses the back button from B, B us destroyed and the user is returned to A. 当用户按下B的后退按钮时,B被破坏,并且用户返回到A。

However, there is a case where B needs to re-create itself. 但是,在某些情况下,B需要重新创建自己。 To do this, I call finish() and then startActivity() on B and that works fine. 为此,我在B上调用finish() ,然后调用startActivity() ,这很好用。 But then, when I click the back button, it shows B again, and so I need to click the back button once more to get back to A. 但是,当我单击“后退”按钮时,它再次显示B,因此我需要再次单击“后退”按钮以返回到A。

How can I re-start B, but still be able to press the back button only once to return to A? 如何重新启动B,但仍然只能按一次返回按钮返回A?

The following will dispose of the current activity while launching the next intent: 以下将在启动下一个意图时处理当前活动:

Intent launchNext = new Intent(getApplicationContext(), NextActivity.class);
launchNext.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(launchNext);

To override the back button, use the following: 要覆盖后退按钮,请使用以下命令:

@Override
public void onBackPressed() {
    super.onBackPressed();
    this.finish(); // or do something else
}

This can be solved by taking a closer look at your intent flags. 这可以通过仔细查看您的意图标志来解决。 Check out http://developer.android.com/reference/android/content/Intent.html and they give more information about what lifecycle you are shooting for. 查看http://developer.android.com/reference/android/content/Intent.html ,它们会提供有关您要拍摄的生命周期的更多信息。

Also, don't forget that you can override the back button functionality. 另外,不要忘记您可以覆盖后退按钮功能。 This may be helpful in case you want to manage your life cycle more closely. 如果您想更紧密地管理生命周期,这可能会有所帮助。 For example, you can also make sure to go back to A if back from B. And close your app if back on A. 例如,您还可以确保从B返回到A。如果回到A,则关闭您的应用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM