How to exit when back button is pressed?

d-man picture d-man · Mar 1, 2010 · Viewed 122.2k times · Source

When a user presses the back button on an intent, the application should quit. How can I ensure the application quits when the back button is pressed?

Answer

Hugo Matilla picture Hugo Matilla · Apr 11, 2012

In my Home Activity I override the "onBackPressed" to:

@Override
public void onBackPressed() {
   Intent intent = new Intent(Intent.ACTION_MAIN);
   intent.addCategory(Intent.CATEGORY_HOME);
   intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   startActivity(intent);
 }

so if the user is in the home activity and press back, he goes to the home screen.

I took the code from Going to home screen Programmatically