Independent time tracking in android app: service or asynctask?

122 views Asked by At

I'm trying to do a time tracking app: you push "start" on a task, timer launches somewhere, counts its time, after some time limit a notification is shown - "you are late", but timer goes on. App has many activities, timer should update UI on one of them. An it should count time regardless user's actions, passing between activities, incoming calls, configuration changes or leaving the application.
What's the best way to do this? I'm thinking on a Service and BroadcastReceiver to update UI, but I don't know how to protect it from being stopped.

1

There are 1 answers

0
Frank D. On BEST ANSWER

A Service with a BroadcastReceiver would be a good solution for a background timer that sends UI update messages to your Activity. You probably looked here. Your question is not very specific, so I cannot provide any code, but I'll try to give you a recipe and considerations to get you on your way building a timer Service:

Your timer Service has to work in the background, regardless of user actions or other apps that may be started or when the phone turns to sleep-mode. Once your Service is started from an Activity, your Service will start doing it's counting (I recommend using a Handler and it's postDelayed() functionality for this). You'll need to use the BroadcastReceiver to send UI update commands from the Service to your Activity. Be sure to disconnect the Receiver in your Activity's onPause() and reconnect in the onResume() method so you can safely switch between activities or exit your app.

You'll need a partial Wakelock to prevent your Service from stopping when the device goes into sleep-mode.

Your Service may also be stopped by the Android system or even by the user from the control panel. In the onStartCommand() function you can return the flag START_STICKY to automatically restart your Service in case of such events.

You should be aware that when your Service is done performing it's task, it should always stopSelf() to avoid battery drain issues.