4

After logout the user is directed to login screen in android. Now, if user clicks on back button of phone it should stay on login screen itself.

How can I make it possible in android?
I have used following code in my application but it will close my application. It should stay on the login screen only

Intent objsignOut = new Intent(getBaseContext(),Hello.class);
objsignOut.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(objsignOut);

Please guide me the correct way.

Vincent P
  • 426
  • 3
  • 16
Smily
  • 2,646
  • 4
  • 23
  • 31

5 Answers5

7

override the onBackPressed in your login activity, to do nothing..

public void onBackPressed() {
    //do nothing
}
Nermeen
  • 15,883
  • 5
  • 59
  • 72
  • 5
    It's misleading - when you open app first time you can't back to system using back button. More safe is using flags on start activity -> http://stackoverflow.com/a/14697271/2140160 – Mr Jedi Oct 13 '15 at 10:50
5

It seems to me that there are simpler and cleaner solutions than overriding onBackPressed method, as mentioned here and here.

You can provide flags when launching a new activity (on login or logout) to simply clear the "back-stack" rather than override the behavior for the back-button:

intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);

This is a safer solution that can also be used after you log-in and not just after you log-out.

Dean Gurvitz
  • 854
  • 1
  • 10
  • 24
1
public void onBackPressed(){
    if(appCanClose){
        finish();
    }
}

These functions can exist in both the system framework (used if not in your code), as well as in your code. If you leave it empty, the app will do nothing when the back button gets pressed.

In this example, when the boolean value appCanClse is true, the back button will quit the app, if false, the back button wil do nothing. I would make sure the user still has someway to quit the app. :p

Matt Clark
  • 27,671
  • 19
  • 68
  • 123
1

You can do it by just adding this two line of codes

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

}

It will prevent going back to previous activity as well as take the app to background when anyone hits back button

MrinmoyMk
  • 551
  • 7
  • 21
0

The actual solution is

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

add this code in Login Activity. App closes when back button clicked in login page.

Athira
  • 1,177
  • 3
  • 13
  • 35