0

I have a login form and a button which when click starts another activity. But after pressing the back button on the bottom left of the phone, it navigates back to the login activity. How can I prevent this. This is what I've been working with :-

loginButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        startActivity(new Intent(LoginActivity.this, HomeActivity.class));    
    }
});
Miss Chanandler Bong
  • 4,081
  • 10
  • 26
  • 36
Anit Aggarwal
  • 143
  • 2
  • 2
  • 9

3 Answers3

2

Just close the activity that you no longer need using finish()

loginButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
    startActivity(new Intent(LoginActivity.this, HomeActivity.class));
    finish();
   }
});
Adam Ma
  • 624
  • 5
  • 16
  • it does stop back navigation. When back button is pressed, the app minimizes and then when the ap is restored. It again opens a the login page. How to prevent that ? – Anit Aggarwal Apr 13 '20 at 00:11
  • 1
    That is the expected behaviour of back button on an Android device as it destroys the activity, you can look for how to override back button, but I would suggest, saving logged state of a user and check it once the app is launched, if he is logged, straight away start home activity and pass his details if needed – Adam Ma Apr 13 '20 at 08:50
1

Try adding Intent.FLAG_ACTIVITY_CLEAR_TOP and Intent.FLAG_ACTIVITY_NEW_TASK. See the example bellow:

Intent intent = new Intent(this, A.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); 
    startActivity(intent);
Pedro Massango
  • 4,114
  • 2
  • 28
  • 48
1

startActivity(new Intent(LoginActivity.this, HomeActivity.class)); finish ();//try this

Shivam
  • 113
  • 7