Wozza
Wozza

Reputation: 622

android game - keeping track of time

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.

Upvotes: 4

Views: 3912

Answers (2)

Sherif elKhatib
Sherif elKhatib

Reputation: 45942

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.

Upvotes: 9

Yashwanth Kumar
Yashwanth Kumar

Reputation: 29131

shared preference seems a better idea to me.

  1. calculate the time difference in onPause() , when the game goes to background, assuming user is already playing game. Add this difference to the previous time in the shared preference and store it again.

  2. start the clock again on onResume() and repeat step 1 if necessary.

I hope you get the idea.

Upvotes: 2

Related Questions