1

I wrote a game where I have activity A (main menu) and activity B (game screen).
Sometimes Android can kill my application. Then, when it's restarted, Android tries to restore activity B with default values, which are of course invalid at this time.
I know I should save and restore instance state, but there are too many variables and other things to care about, I just don't want to do it.
I am saving game progress in onStop() method, so instead I would like to simply finish activity B when system tries to restore it, and return user to the main menu from where he could load last saved game.

Long story short, I wrote this code and it works. But I'm not sure if this code is safe and will work correctly in all situations.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState!=null) {finish(); return;}
    ....
dop2000
  • 577
  • 1
  • 7
  • 17

1 Answers1

0

To make it cleaner and avoid unintended problems later, I'd suggest that you pass a boolean to onSaveInstance() and read it back in onCreate(), and based on that finish() your Activity.

Vikram Bodicherla
  • 7,133
  • 4
  • 28
  • 34
  • What if I get a savedInstanceState without my boolean? I will still need to finish() the activity. So what's the point in this boolean? – dop2000 Jan 31 '12 at 07:59
  • onSaveInstance() is invoked when an Activity is killed. So you set a boolean (or any marker object) in the Bundle passed to onSaveInstance() to mark this Activity as killed. Now in onCreate() you'll know if the Activity was killed based on the presence of this marker object. Does that make sense? Am I missing anything here? – Vikram Bodicherla Jan 31 '12 at 09:02
  • As far as I understand, activity only gets Bundle in onCreate() when it's restored after it was killed. So I can simply check that bundle!=null – dop2000 Jan 31 '12 at 09:59
  • Yea you are right. I was unnecessarily complicating the solution – Vikram Bodicherla Jan 31 '12 at 13:08