简体   繁体   中英

How to stop app from restarting when user presses the back button

I am working on a small app. When the user presses the app icon it starts activity A, which in turns starts activity B. Activity A then completes. B is set up as a main menu and can start other activities: the user can navigate back to B with the back button.

If the user navigates back to B and presses the back button the app moves into the background and the user is at their home screen. I have not overridden anything; this is the normal navigation.

At this point, if the user presses the app icon the app restarts. I understand that when the app is in the background the OS can close it for memory purposes, but this happens every time - regardless of how much memory. Is there a way to change this behavior? I already figured out how to stop this action with the home button with:

if (!isTaskRoot())

But I need to stop the action on the back button.

You can override onBackPressed() of Activity B like this,

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

The app will be hidden when the user presses the back button, but it's state will remain the same. And when it is reopened, it will appear just as it was when you left it.

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