DRing
DRing

Reputation: 7039

CountDownTimer service

Im trying to make a countdown timer run in the background of my activity, it needs to run constantly until it finishes, but not sure how to make it work with a service. I also need to update the display on my main activity

Upvotes: 1

Views: 1758

Answers (1)

Joe Malin
Joe Malin

Reputation: 8641

Uh, not all services run 100% of the time. Nothing is a battery drain unless it's executing at 100%. If you look at the actual battery consumption of an Android device, you'll see that the largest percentage comes from the screen. The next comes from radios. Running a process costs very little.

You can use an IntentService to fire off an alarm at regular intervals. The service can send intents to itself. Have one intent action to start the service, and one to turn off the alarm. Make a third action for resetting the alarm.

To start the service, send a "start" intent to the IntentService using startService(intent). This should trigger a method that creates an intent with action "cycle", puts the intent in a PendingIntent, and schedules a repeating alarm with AlarmManager.setRepeating().

After the interval that you set for the alarm, the AlarmManager will take the "cycle" intent out of the PendingIntent and send it back to your service. Your service should handle "cycle" by rebuilding the PendingIntent and restarting the alarm. This goes on indefinitely. You can put anything else you want to do when the alarm goes off in the handling for the "cycle" action.

When you want the alarm to stop, send the "stop" intent. In response, your service should cancel the alarm by reconstructing the PendingIntent and then calling AlarmManager.cancel().

Notes: The main entry point for an IntentService is onHandleIntent(). You call everything else from there. When that method finishes, the service goes inactive until it receives another intent. The only place you can "see" it is in cached processes. Once you stop the alarm, the system will eventually figure out that the service isn't being used, and garbage-collect it.

Services are the way to do background work. I suppose you can run some AsyncTask or a thread, but you still want to run them in a Service, otherwise you've linked them to something that's running in the foreground. If the task doesn't need to interact with the user, particularly if it can work asynchronously to your activity, then use a service.

Upvotes: 1

Related Questions