I have a puzzle game for android. When the puzzle starts I take the current time:
long startTime = System.currentTimeInMillis()
When the player completes the puzzle, I take the time again, subtract the starting time and work out the elapsed time. This is all ok.
My problem is what to do when the application is interrupted. For example by a phone call. At the moment, the puzzle remains in it's previous state automatically (as it is in a view). However, the calculation completionTime = currentTime - startTime
will now be invalid.
I have tried saving the elapsed time using onSaveInstaceState(Bundle)
. However its counterpart, onRestoreInstanceState(Bundle)
is not called when re-entering the app. Rather, the onResume()
method is called instead? I have read this is because the app has not been 'killed', rather it is still in memory. In the case of a 'kill', I'd imagine the state of the View will also be lost? I don't think it's terribly necessary to keep track of the view in this case, so I won't worry about the time either.
Is there a way to read a bundle from onResume(), should I just implement a shared preference?
I'd like to avoid updating the elapsed time in the game loop as this seems inefficient.
I would advice not using a SharedPreference at all.
You will only need 2 fields: startTime
and elapsedTime
When the player starts, initialise elapsedTime
to 0
and startTime
to System.currentTimeMillis()
When onPause()
is called, initialise elapsedTime
using
elapsedTime = elapsedTime + (System.currentTimeMillis() - startTime);
When onResume()
is called, initialise startTime
to System.currentTimeMillis()
When the player is done, the time is
elapsedTime = elapsedTime + (System.currentTimeMillis() - startTime);
Please, if the logic has a flaw, comment (:
Note: There exists a way to use only one field.! But we'll keep that for the reader to discover.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With