I am developing an android game in which a global variable must gradually increment over time, with a varying increment amount. This variable will act as the player's 'resources', which they can then spend how they wish.
This is simple enough to achieve using a timer task - but is only effective whilst the app is in the foreground. As soon as the app is closed, this 'resource' variable will cease to increment.
The logic I have tried so far is to record the current time on the onPause() event. Then, on the onResume() event, retrieve the recorded time and compare it with the current time using:
DateTime lastPaused = getLastSyncTime(); // stored in db
Seconds secs = Seconds.secondsBetween(lastPaused, DateTime.now());
resource = resource + (gainPerMinute * (secs / 60));
updateResources(resource);
setSyncTime(DateTime.now());
However, I feel like this method could be improved upon. One problem I face is that using jodatime
's DateTime
, there doesn't seem to be a Milliseconds
class like there is for Seconds
. So when the time difference is rounded the nearest second, the player actually stands to lose/gain some resources, depending on whether the duration is rounded up or down.
I'm not happy with my current approach. I'm positive that there is a more precise, more reliable way of maintaining a variable that should be constantly incrementing. Any suggestions would be appreciated.
Services don't come up with any UI so you will have to bind them/or use broadcast with activites.which in turn display the values in the UI after communicating with each other .To start a service from an activity .
now the service has started....
inside the service read the data which had been passed earlier
But sending data using the above method just sends the value only once that is during the start of the service,but in your case you would constantly want to send and receive the data....
so inside the service whatever you are calculating needs to be constantly sent to the activity so that UI can be updated and other things can be done ,in that case you will also like to use a broadcast
///
put the above two lines inside a method which is called whenever a change happens,say when a button is clicked or timerischanged for e.g
now go inside the activity again register the broadcast inside the activity
now create this method
//
if my answer was helpful upvote and accept it please