0

I having the next problem. I’m developing a game. When I lock the device from the physical button and unlock it, the game starts again. The activity starts again. When I unlock it I want to continue playing from the moment I lock it.

user3240604
  • 407
  • 1
  • 8
  • 22

2 Answers2

0

Then you need to save the state in onPause and load it again in onResume

ligi
  • 39,001
  • 44
  • 144
  • 244
0

you need to save and restore state of your activity using onSaveInstanceState and onRestoreInstanceState

enter image description here

save:

static final String STATE_SCORE = "playerScore";
static final String STATE_LEVEL = "playerLevel";
...

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Save the user's current game state
    savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
    savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);

    // Always call the superclass so it can save the view hierarchy state
    super.onSaveInstanceState(savedInstanceState);
}

restore:

public void onRestoreInstanceState(Bundle savedInstanceState) {
    // Always call the superclass so it can restore the view hierarchy
    super.onRestoreInstanceState(savedInstanceState);

    // Restore state members from saved instance
    mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
    mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
}
Rahul Tiwari
  • 6,851
  • 3
  • 49
  • 78
  • Yes but in my activity i have like 100 variables, there must be an easy way – user3240604 Oct 20 '15 at 14:47
  • you can try storing your variables to shared preferences each time they change. again even that will not be easy. I can't think of any other way as of now. instance state is the one recommended. – Rahul Tiwari Oct 20 '15 at 14:49
  • also, you need to carefully choose which variables to preserve, if you look carefully you may found you need not to preserve all of them – Rahul Tiwari Oct 20 '15 at 14:51
  • is there a way to know if the pohone was lock and unlock in the onResume method? After i unlock the cellphone i want to know ask for that, because onResume i have a method that start all again – user3240604 Oct 20 '15 at 14:53
  • you mean to say you are restarting everything in onResume by your code? http://stackoverflow.com/a/11623910/1529129 this might help you – Rahul Tiwari Oct 21 '15 at 06:31
  • Yes, thats the problem! – user3240604 Oct 22 '15 at 19:11