Reputation: 3760
I need a background service that has to be started at an exact time by a timer, and then should continuosly run until another exact time doing its task, except than this task can be stopped by the user from an Activity.
If multiple timers fire at the same time, the service has to execute all the jobs in parallel and then stop itself at the end of all jobs.
What I should use to accomplish this? A Service
? An IntentService
? Another type of background task?
And then, how could I stop each of the tasks, without bothering the others in execution? Is there a way to link each of these service instance to a database entity, so that I could stop the task when the user wants?
Upvotes: 0
Views: 579
Reputation: 104
IntentService will not help you in achieving your task. There is only one instance of an IntentService at a time. In case of multiple events getting fired, all these events will go to a queue from which they will be executed serially. So your parallel execution requirement is not fulfilled here.
One of the best way I think you can achieve this by using AsyncTask. Fire an AsyncTAsk on completion of timer, do your background work in doInBackGround, and cancel the task whenever you want. Also internally AsyncTask maintains its own thread pool. So you need not worry about creating multiple thread and clogging resources.
AsyncTask may lead to a few problems and have a few issues while canceling, and state change. For starters it will do the trick.
Refer : https://developer.android.com/reference/android/os/AsyncTask.html
Also if you want to explore the best way of doing it I would say go with RxAndroid. It handles all the shortcomings of AsyncTask and fullfills all your requirements quite easily. For comparison between best practices for Async programming in android refer: http://code.hootsuite.com/asynchronous-android-programming-the-good-the-bad-and-the-ugly/
You can refer: https://github.com/ReactiveX/RxAndroid You can find a lot of tutorials around.
Upvotes: 2