The application looks something like this: MainActivity -> UserActivity -> DetailsActivity. (approximate order of activities).
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?
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);
And in the same activity in onCreate
:
if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
}
So you clear the stack and then kill the single one left... you can do this in any activity and of course use it in onBackPressed
:)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With