Android – How to prevent going back to the previous activity

activity-stackandroidbackback-stack

When the BACK button is pressed on the phone, I want to prevent a specific activity from returning to its previous one.

Specifically, I have login and sign up screens, both start a new activity called HomeScreen when successful login/signup occurs. Once HomeScreen is started, I want to prevent the users from being able to return to the login or sign up screens by pressing the BACK key.

I tried using Intent.FLAG_ACTIVITY_NO_HISTORY, but since the application has Facebook integration, when the 'Login with Facebook' is used, Facebook should return to the initial login screen, therefore I should keep a history of these activities.

I thought of overriding the behaviour of the BACK button on HomeScreen to directly finish an application when the button is pressed and I used

@Override
public void onBackPressed() {
    finish();
}

but that also does not work.

Best Answer

My suggestion would be to finish the activity that you don't want the users to go back to. For instance, in your sign in activity, right after you call startActivity, call finish(). When the users hit the back button, they will not be able to go to the sign in activity because it has been killed off the stack.