Jesús Ayala Jesús Ayala - 3 months ago 5
Android Question

How to exit from Android App even if current Activity is not Main Activity

I have this activity flow

HomeActivity > Activity1 > Activity2 > Activity3 > HomeActivity

I switch back directly from Activity3 to HomeActivity by pressing cancel button on Activity3.

but when I press back button on HomeActivity I want to exit from the app, however it takes me back to Activity3... how to exit the app??? this is my code
on Home activity:

@Override
public void onBackPressed() {
finish();
System.exit(1);
}


if I press back button when App is just started on HomeActivity it works normally, closing the app...

How to make it work when I navigate through all these other activities?

Answer

You should switch from Activity3 to HomeActivity this way:

Intent launchNextActivity = new Intent(Activity3.this, HomeActivity.class);
launchNextActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
launchNextActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);                  
launchNextActivity.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(launchNextActivity);

Then onBackPressed() should work fine.