Press the back button once and exit the application

60 views Asked by At

I have four activities: activity 1, activity 2, activity 3 and activity 4.
When I open the app, I find myself in activity 1, then step into activity 2, then step into activity 3 and finally step into activity 4.
When I'm in activity 4 there's a button that sends me to activity 1, if I press the "Back" button back to activity 4.
I would like that when I step from activity 4 to activity 1, if I press the "back" button while I'm in activity 1 I go out of the loop.
My question is about I do not want to go back, I want to get out of the app when I press "back" in activity 1.

Can you give me some advice on how to do it?

2

There are 2 answers

0
Ankit Mehta On BEST ANSWER

You can override onBackPressed() method of Activity1 and inside this put following code :

@Override
public void onBackPressed()
{
     // code here depending on your needs
    ActivityCompat.finishAffinity(this);
    finish();
}

Also you can try following :

   @Override
   public void onBackPressed()
   {
        startActivity(new Intent(this, HomeActivity.class).
        setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK).putExtra(EXIT_FLAG, true));
   }
0
Vasco Lopes On

If your wish is to on back click don't go to other activity, you should use finish() when starting a new activity. This will force android to not put the activity-parent (the one who created the new one) in the "back" stack.