4

I am logging each onCreate() and onDestroy() calls. I found out that once I click power button on my Android (and on the emulator too!) the phone calls in my activity

> onDestroy();
> onCreate();

Which kills my game and then immediately reopen it from the beginning. Of course once user unlock the screen the game is presented in main menu with all progress killed.

Is it possible to override or disable this behavior?

PiotrK
  • 4,210
  • 6
  • 45
  • 65
  • 3
    why don't you save the progress in the onDestroy() method and check for a saved game (and restore the progress) in the onCreate() method? – ethan Nov 28 '11 at 20:59

2 Answers2

11

When you press the power button, the screen lock usually kicks in. This may trigger a configuration change on the activity currently in the foreground (the screen lock is usually in portrait mode), causing it to be destroyed and recreated.

Declaring android:configChanges="keyboardHidden|orientation" for such activities in AndroidManifest.xml prevents them to be destroyed and recreated but also implies that you will handle the configuration changes by yourself (if necessary) by overriding onConfigurationChanged

sfera
  • 1,138
  • 1
  • 15
  • 21
  • 5
    This is the correct answer! Note however that if you are targeting API 13 or greater then pressing the power button will also trigger a change in 'screenSize'. Hence this also needs to be overridden to get the desired behaviour: android:configChanges="keyboardHidden|orientation|screenSize" – Twice Circled Dec 27 '12 at 18:08
  • I didn't noticed the screenSize change on API13, added it solved the problem for me, thanks. – Vince Jan 04 '13 at 10:13
3

You can't override when the onCreate() and onDestroy() methods get called (at least not without experiencing extraordinary amounts of pain). The best thing for you to do is to figure out how to work within the confines of when they get called. Save your state in onDestroy(). Make it so that your app can tolerate this call sequence because quite frankly, it supposed/has to. That's just how android works.

Kurtis Nusbaum
  • 30,445
  • 13
  • 78
  • 102
  • How can I detect that this call comes from power button? – PiotrK Nov 28 '11 at 22:39
  • As far as I'm aware, you can't. But that's ok, because in the end it shouldn't really matter why `onDestroy()` or `onCreate()` were called, just that they were called. – Kurtis Nusbaum Nov 28 '11 at 22:56