4

I basically want to create a timer. I have a textview where I need to show a timer like "Updating your location in 2min 29 secs" and I want the timer to decreament For eg 2min 28secs followed by 2min 27 secs.

And I want to update it even when the user is not using my app (I dont want it to update in real sense what I mean is when user opens my app after say 1 min then the timer should show 1min 27 secs).

Can some one please help me out in pointing out the correct and efficient way of doing this ? Thanks :)

ik024
  • 3,566
  • 7
  • 38
  • 61

2 Answers2

2

The most efficient way in my opinion is using scheduleAtFixedRate when your activity is in foreground and when it is going to background you do not need any services you can just save the current time and the remaining time in a sharedpreferances and when again your activity comes to foreground read those values plus current time and then update the textview in a proper way.

mmlooloo
  • 18,937
  • 5
  • 45
  • 64
1

You could use a service and send intents that your activity receives (the one with the TextView) using LocalBroadcastManager. You should register a BroadcastReceiver inside Activity.onResume(), and unregister it inside onPause().

Using a TimerTask should be the default approach but you must be aware that if your activity is sent to background it can be killed by the system. That's why I recommend using a service.

Hope it helps.

Junior Buckeridge
  • 2,075
  • 2
  • 21
  • 27
  • hey thanks for the ans. I do have one question though. Is it okay to broadcast intents every sec? since I want my textview to update by sec not by min. – ik024 Oct 15 '14 at 03:57
  • You could toggle a flag in the application object that indicates if activity is *resumed* or *paused*. Checking that will allow you to broadcast from your service only when the activity is in foreground. – Junior Buckeridge Oct 15 '14 at 04:01