-1

This is a small question but I'm finding very hard to solve this. I have multiple activities. For example A B and C. When app is launched A is opened and on click of button will redirect me to activity B and then from B on click of another button will take me to C. On Back pressed will now bring me back to B and again on Back button is pressed will take me to A which is main Activity.

Now if I press back button, instead the app should exit...it creates loop between B and A and never exit the app.

I already used the following method

Method 1: use of this.finishonBackPressed which didn't help

Method 2: use android:nohistory = true in manifest

But If I do so then from C activity it will directly take me to A which I don't want.

Method 2. Use of

      Intent intent = new Intent(Intent.ACTION_MAIN);
        //to clear all old opened activities 
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        finish();

when I use this then everytime this opens up in my device enter image description here

Please anyone help.

This is my code in Mainactivity now

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

But also it don't work and it creates loop between A and B Activity.

ʍѳђઽ૯ท
  • 16,646
  • 7
  • 53
  • 108
Bir Nepali
  • 429
  • 1
  • 8
  • 20
  • 1
    I'd first ask why you need to exit anything. This simply smells like bad design – Marcin Orlowski Sep 17 '18 at 20:34
  • 2
    you are not supposed to prohibit the user to exit the app by looping through activities. – peshkira Sep 17 '18 at 20:38
  • No I don't want user to loop thorough the activities..when user is in main activity ..user should be able to exit the app but instead it opens the previous activity and looping start to occur. – Bir Nepali Sep 17 '18 at 20:41
  • @peshkira yes I want the same..without looping I want user to exit the app when he /she is in Mainactivity but it open previous activity instead. – Bir Nepali Sep 17 '18 at 20:44
  • just remove the override of onBackPressed in the MainActivity then. Or don't call finish() in onBackPressed(). – peshkira Sep 17 '18 at 20:45

1 Answers1

9

Your code (in MainActivity) is incorrect , put finish() after super.onBackPressed()

it must be :

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