Android close app on back button

You can accomplish that by overriding the back button event to add no history for specific activity on specific condition.

@Override
public void onBackPressed()
{
    if ( ! getIntent().getExtras().getBoolean(FROM_SETTINGS_KEY))
        moveTaskToBack(true); // exist app
    else
        finish();
}

in my example it check for a flag that is from where i had launched my activity, if launched from settings then act normally, else make it on top and exit app on back pressed


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

Tags:

Android