Search code examples
androidandroid-activityactivity-stack

How to navigate forward between activities while discarding a login screen from the stack?


I have an app that if I am on a certain screen, and the user tries to access a specific part of the app that needs auth, it goes to the log in screen before continuing.

What the app currently does is, say I am on screen 3, but want to go to screen 4, but I need to login first to get to screen 4. The login screen is shown and once logged in, the user is redirected to screen 1 having to go back through the steps to return the screen they were on.

What I want is, when the user clicks the button to go to screen 4, the login screen is displayed, and once logged in, the user is sent to screen 4, with out going back to screen 3 then clicking the button again.

What I have tried is calling finish(); once the user is successfully logged in but all the does is return the user to screen 3, making them have to click on the button to go to screen 4, which of course allows them now because they are logged in.

Got any ideas how I can implement this in my app?

Thanks

EDIT: Title might be misleading, I couldn't think of a better way to reword the title. If you can please go ahead and request an edit


Solution

  • First declare

    int SIGN_IN_REQUEST = 42;
    

    When the user wants to go to screen 4 :

    if (isSignedIn) {
      intent = new Intent(this, Screen4Activity.class);
      startActivity(intent);
    } else {
      intent = new Intent(this, SignInActivity.class);
      startActivityForResult(intent, SIGN_IN_REQUEST);
    }
    

    Finally, have a

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == SIGN_IN_REQUEST) {
          if (resultCode == Activity.RESULT_OK) {
            //User signed in, launch Screen4
            intent = new Intent(this, Screen4Activity.class);
            startActivity(intent);
          } else {
            //User cancelled the sign in, deal accordingly
          }
        }
    }
    

    And from your SignInActivity, if user signed in :

           setResult(RESULT_OK);
           finish();
    

    Otherwise :

           setResult(RESULT_CANCELED);
           finish();