背面按钮的Andr​​oid关闭App背面、按钮、Andr、oid

2023-09-04 05:04:02 作者:邪魅

应用程序看起来是这样的: MainActivity - > UserActivity - > DetailsActivity。 (活动大致顺序)。

The application looks something like this: MainActivity -> UserActivity -> DetailsActivity. (approximate order of activities).

我想关闭该应用程序被点击DetailsActivity时,后退按钮(第三个活动的行中)。

I would like to close the application when the back button is clicked in DetailsActivity (third activity in the row).

想知道,如果它是很好的做法,以做到这一点,什么是做到这一点的最好方法是什么?

Wanted to know if it's good practice to do that and what would be the best way to do that?

推荐答案

如果我理解正确的话,你要关闭的活动,即使栈不为空,这意味着在堆栈超过1活动?

If I understand you correctly, you want to close activity even when the stack isn't empty, meaning there is more than 1 activity in stack?

那么,如果只有一个...只是:

Well if there is only one... just :

finish();

否则,诀窍是:

Otherwise the trick is :

Intent intent = new Intent(Main.this, Main.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);

和在同一个活动的onCreate

if (getIntent().getBooleanExtra("EXIT", false)) {
    finish();
}

所以,你清除栈,然后杀死一个一个离开...你可以在任何活动做到这一点,当然在 onBack pressed 使用它: )