Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android close app on back button

Tags:

android

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?


1 Answers

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 :)

like image 138
Jony-Y Avatar answered Sep 09 '25 15:09

Jony-Y