0

When I am in the MainActivity of my app and press the phone Back Button and open the app again (without closing it before), then the main activity is loaded new.

When I click instead of the back-button on the home-button of the phone, then this doesn't happen. So when I open the app again (by e.g. clicking on the icon) everything stays as it was before clicking the homebutton.

How can I avoid everything to be loaded new when clicking the back-button and then opening the app again?

If you don't know what I mean: pic

The left button is what I mean with "back-button" and the one in the middle is the "home-button".

mathematics-and-caffeine
  • 1,664
  • 2
  • 15
  • 19

2 Answers2

1

I would probably accomplish this by saving the instance state when onBackPressed is called by overriding the function. It's the function called when the back button is pressed and the default behavior is to finish the activity, and that's why you're seeing this behavior.

See: https://developer.android.com/reference/android/app/Activity#onBackPressed()

jack
  • 573
  • 4
  • 12
  • Is there a similar function for the home-button? So that I copy its content and paste in the onBackPressed method. – mathematics-and-caffeine Jan 10 '20 at 17:41
  • There is no such function for the home button, but pressing the home button will cause onPause() and onStop() to be called (sometimes onDestroy() will also be called). What's different with when onBackPressed is called is that it definitely calls onDestroy(). You might just want to save the app state in onDestroy() and then reload it when the app is resumed. You should check out the Android Lifecycle documentation: https://developer.android.com/guide/components/activities/activity-lifecycle – jack Jan 10 '20 at 17:46
  • 1
    Hey, thank you very much. Now I found a solution. It's not yours, but your hint to override the onBackPressed method got me to the solution! – mathematics-and-caffeine Jan 10 '20 at 17:48
  • 1
    Great to hear! I didn't know about `moveTaskToBack()`, so thanks for introducing me to it :) – jack Jan 10 '20 at 17:54
1
@Override
public void onBackPressed() {
    // Behaves like you would have pressed the home-button
    moveTaskToBack(true);
}
mathematics-and-caffeine
  • 1,664
  • 2
  • 15
  • 19