简体   繁体   中英

How to exit an app when Back Button is pressed

This is a small question but I'm finding very hard to solve this. I have multiple activities. For example AB 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.finish onBackPressed 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在此处输入图片说明

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.

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

it must be :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM