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.
-
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
-
1use 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 Answers
add finish();
in login activity and add onBackPressed in your next activity
@Override
public void onBackPressed() {
}

- 295
- 1
- 6
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.

- 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
-
1Standard 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
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>

- 5,957
- 2
- 15
- 32
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.

- 1
- 1