How to Exit android app on back pressed?

Some times we don't want to open activities after pressing back button, examples Splash Screen Activity, Welcome Screen Activity, We don’t need these activities in activity stack.


we can remove it from activity stack by below ways

Manifest file
android:noHistory="true"

<activity
    android:name="com.example.activity"
    android:label="" 
    android:noHistory="true">
</activity>

 

Some times we want to close entire application on back press
just place this code in onBackPressed method

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

 

or we can do by

public void onBackPressed() {
  finish();
}