Android game - time tracking

I have a puzzle game for Android. When the puzzle begins, I take the current time:

long startTime = System.currentTimeInMillis()

When the player completes the puzzle, I again take the time, subtract the start time and worked out the elapsed time. Everything is good.

My problem is what to do when the application is interrupted. For example, by phone. At the moment, the puzzle remains in its previous state automatically (as you can see). However, the calculation of completionTime = currentTime - startTime will now be invalid.

I tried to save the elapsed time using onSaveInstaceState(Bundle) . However, its duplicate onRestoreInstanceState(Bundle) not called when you re- onRestoreInstanceState(Bundle) application. Rather, the onResume() method is called instead? I read this because the application was not "killed", rather, it is still in memory. In the case of a โ€œmurder,โ€ I would suggest that the state of the submission will also be lost? I donโ€™t think it is terribly necessary to keep track of opinions in this case, so I wonโ€™t worry about time either.

Is there a way to read the package from onResume (), should I implement general preferences?

I would like to avoid updating the elapsed time in the game loop, as this seems inefficient.

+4
source share
2 answers

I would advise against using SharedPreference at all.


You will need only two fields: startTime and elapsedTime

When the player starts the game, initialize elapsedTime to 0 and startTime to System.currentTimeMillis()

When onPause() is called, initialize elapsedTime using

 elapsedTime = elapsedTime + (System.currentTimeMillis() - startTime); 

When onResume() is called, initialize startTime to System.currentTimeMillis()

When a player is done, time

 elapsedTime = elapsedTime + (System.currentTimeMillis() - startTime); 

Please, if the logic has a flaw, a comment (:

Note. There is a way to use only the one field.! But we will keep it for reading by the reader.

+9
source

general preferences seem to me more useful.

  • calculate the time difference in onPause () when the game goes to the background if the user is already playing the game. Add this difference in the previous time to the general setting and save it again.

  • run the onResume () clock again and repeat step 1 if necessary.

Hope you have an idea.

+2
source

Source: https://habr.com/ru/post/1381506/


All Articles