4

In my app, I want to prevent the user from going back to login activity after logging in, but I don't want to close the app. For example if the previous activity is login activity, I don't want to do anything when the user presses back, just stay in the current activity/fragment.

Haem
  • 929
  • 6
  • 15
  • 31
Artiom
  • 513
  • 1
  • 4
  • 15
  • Possible duplicate of [Clicking the back button twice to exit an activity](https://stackoverflow.com/questions/8430805/clicking-the-back-button-twice-to-exit-an-activity) – Haem Jul 27 '18 at 14:04
  • 1
    use finish(); when they are done the log in and don't allow a back button on the main page that way they cant go back – Nigel Brown Jul 27 '18 at 14:08

4 Answers4

3

add finish(); in login activity and add onBackPressed in your next activity

  @Override
    public void onBackPressed() {

    }
0

The correct way to do this is to call finish() in the Login activity when it completes and launches the next activity. For example:

Intent intent = new Intent(LoginActivity.this, NextActivity.class);
startActivity(intent);
finish();

This would prevent the user from going back from NextActivity to LoginActivity since calling finish() destroys LoginActivity and removes it from the back stack.

There is no need to remove onBackPressed from NextActivity, and that may have unintended consequences (for example, if they navigate from Login -> Next -> Other -> Next then click back, they would expect to go back to Other). Disabling onBackPressed in Next would prevent that.

Tyler V
  • 9,694
  • 3
  • 26
  • 52
  • thats right, but if i use back button in the next activity, it will close the app, but i want to stay in this current activity – Artiom Jul 27 '18 at 14:21
  • 1
    Standard Android behavior is to close the app if you press back and the back stack is empty. If you want non-standard behavior, you can override `onBackPressed` (may confuse users though). One option would be to pass some data in the intent from Login to Next to indicate whether to disable the back button or not. – Tyler V Jul 27 '18 at 14:24
0

Add android:noHistory="true" in the manifest of your LoginActivity

<activity android:name=".LoginActivity" android:noHistory="true">
  <intent-filter>
    <action android:name="android.intent.action.MAIN"/>
    <category android:name="android.intent.category.LAUNCHER"/>
  </intent-filter>
</activity>
shb
  • 5,957
  • 2
  • 15
  • 32
0

Just remove the super.onBackPressed like:

@Override
    public void onBackPressed() {
    //super.onBackPressed();
    . . .
}

It will only detect when user clicks back button, and doesn't close the app.

aladium
  • 1
  • 1