How to prevent going back to the previous activity?

196,165

Solution 1

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.

Solution 2

Following solution can be pretty useful in the usual login / main activity scenario or implementing a blocking screen.

To minimize the app rather than going back to previous activity, you can override onBackPressed() like this:

@Override
public void onBackPressed() {
    moveTaskToBack(true);
}

moveTaskToBack(boolean nonRoot) leaves your back stack as it is, just puts your task (all activities) in background. Same as if user pressed Home button.

Parameter boolean nonRoot - If false then this only works if the activity is the root of a task; if true it will work for any activity in a task.

Solution 3

I'm not sure exactly what you want, but it sounds like it should be possible, and it also sounds like you're already on the right track.

Here are a few links that might help:

Disable back button in android

  MyActivity.java =>
    @Override
    public void onBackPressed() {

       return;
    }

How can I disable 'go back' to some activity?

  AndroidManifest.xml =>
<activity android:name=".SplashActivity" android:noHistory="true"/>

Solution 4

There are two solutions for your case, activity A starts activity B, but you do not want to back to activity A in activity B.

1. Removed previous activity A from back stack.

    Intent intent = new Intent(activityA.this, activityB.class);
    startActivity(intent);
    finish(); // Destroy activity A and not exist in Back stack

2. Disabled go back button action in activity B.

There are two ways to prevent go back event as below,

1) Recommend approach

@Override
public void onBackPressed() {
}

2)Override onKeyDown method

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if(keyCode==KeyEvent.KEYCODE_BACK) {
        return false;
    }
    return super.onKeyDown(keyCode, event);
}

Hope that it is useful, but still depends on your situations.

Solution 5

Since there are already many great solutions suggested, ill try to give a more dipictive explanation.

How to skip going back to the previous activity?

Remove the previous Activity from Backstack. Simple

How to remove the previous Activity from Backstack?

Call finish() method

The Normal Flow:

enter image description here
All the activities are stored in a Stack known as Backstack.
When you start a new Activity(startActivity(...)) then the new Activity is pushed to top of the stack and when you press back button the Activity is popped from the stack.
One key point to note is that when the back button is pressed then finish(); method is called internally. This is the default behavior of onBackPressed() method.

So if you want to skip Activity B?

ie A<--- C

Just add finish(); method after your startActvity(...) in the Activity B

Intent i = new Intent(this, C.class);
startActivity(i);
finish();

enter image description here

Share:
196,165

Related videos on Youtube

ecem
Author by

ecem

Updated on June 16, 2021

Comments

  • ecem
    ecem about 3 years

    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.

    • havexz
      havexz over 12 years
      Just to clarify, you trying to capture back behavior for everyone except facebook?
    • ecem
      ecem over 12 years
      In some sense yes, but actually what I want is after a successful login occurs and HomeScreen opens, user should not be able to go back to the login screen by pressing BACK button. Just like Twitter or Foursquare for example, once we log in to those apps, we do not see login page until we log off (even if we press BACK after logging in).
  • ecem
    ecem over 12 years
    FLAG_ACTIVITY_NO_HISTORY prevents my LoginScreen to capture Facebook's callback when Login with Facebook is used. Because once the focus goes out of the LoginScreen it cannot be resumed (since there is no history). But I haven't tried it with Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS, I'll check it, thanks!
  • ecem
    ecem over 12 years
    also thanks about the finish() method, I did not know about it.
  • ecem
    ecem over 12 years
    I cannot use the noHistory option because of the Facebook issue which I tried to explain in my question and also one of the comments. But the thing with the BACK button is not disabling it, but making it exit the whole application like System.exit(0) is called (I know it is not the best practive, but I just wanted to give an example).
  • AlleyOOP
    AlleyOOP over 10 years
    What if I would like the thread in the previous activity to remain running?
  • coder
    coder over 10 years
    You wouldn't want to go with my approach then. Calling finish() is going to kill the activity. Could you start your process that you want to run in the activity that you're going to?
  • David Murdoch
    David Murdoch over 8 years
    Note: if you call finish during a shared transition you may get a bleed through of the previous activity. e.g., if you have HomeActivity -> IntermediateActivity -> FinalActivity, and you call finish() in the IntermediateActivity immediately after starting the FinalActivity you'll see the HomeActivity for a brief moment.
  • Hackmodford
    Hackmodford about 8 years
    Perfect for a login screen because it keeps the history intact.
  • DeniSHow
    DeniSHow over 7 years
    Thanks you, I tried to find this for about three days. Because of android:noHistory="true" flag for Activity don't work as expected (noHistory flag recreates activity after minimization) and finish() sometimes don't worked for me, but why I still don't understood.
  • C. Skjerdal
    C. Skjerdal over 6 years
    Is it not bad user experience to disable the onBackPressed()?
  • TylerH
    TylerH almost 6 years
    This is basically what the accepted answer from four years prior said.
  • hyperCoder
    hyperCoder over 5 years
    Thanks this worked great. Only suggestion I'd make here would be, no need for return. Just remove super.onBackPressed();and leave the method blank. That works fine as well
  • user3099225
    user3099225 about 5 years
    It totally depends on what you are trying to make, in app functionility needs this then go for it.
  • varun
    varun about 5 years
    It's amazing how I completely forgot about the first method usingfinish(). Unnecessarily overthought with nohistory attribute, intent flags, parent activity manifest tags, etc! Silly, thanks for the answer!
  • eddym
    eddym over 3 years
    @DavidMurdoch Do you know any solution for that specific case?
  • Elia Weiss
    Elia Weiss over 2 years
    this is partial solution, context doesn't have finish()
  • Rohit Singh
    Rohit Singh over 2 years
    Activity has finish() method.