简体   繁体   中英

How to NOT end the application when Back button is pressed

I am building an app that has 3 screens; the first one is the splash screen the second one is where I need the user to always be and the third one is for setting some things.

When I am at the second screen and I press Back button on android, the application ends. Similarly, when I start the application by tapping on its icon, it starts from the beginning. I do not want that.

All I want is the application to only end when a user ends it himself by going to the application manager in android. Even if the application is running and the user clicks on the application icon, it should go to the current running screen instead of starting it all over.

Best Regards

Just override "onBackPressed" method on second activity

@Override
public void onBackPressed() {
//empty body
}

One alternative is to store a status on SharedPreferences for each activity, for example. And on the onCreate method of the start activity you put something like that before everything:

onCreate() { 
final String status = sharedPreferences.getStatus();

if("secondScreen".equals(status)) {
   Intent intent = new Intent(this, SecondActivity.class);
   startActivity(intent);
   finish();
} else if("thirdScreen".equals(status)) {
   Intent intent = new Intent(this, ThirdActivity.class);
   startActivity(intent);
   finish();
}

//at this point your status it should be the first screen; so go on normally
setContentView();
...

For using the same app instance every time user starts your app, modify the activity declaration in your AndroidManifest.xml:

<activity .... android:launchMode="singleInstance" ...>

For not exiting app on back button, override onBackPressed in your activity:

public void onBackPressed () {
  // do not call super.onBackPressed();
}

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