Android Background Service with Task Queue
My app needs a background service, where I can submit tasks开发者_Python百科 to. The tasks can be quite generic, it might involve downloading feeds, fetching location one time, or fetching resources.This service needs minimal interaction from the activities and it should be started when the app launches and should quit if there is no pending task in the queue.
Is it a good idea? How would I design such a service? All suggestions are welcome
Hoping this architecture will help you:
If you want to perform your task even after your activity is finished then use
startService()
else if you want to terminate all the tasks as soon as activity finishes then usebindService()
.When you call
startservice()
its oncreate() method is not called if the service is already running but itsonStartCommand()
gets called every time you callstartservice()
. You can use this property.You can implement a static method which can be accessed from your activity to put task in it and when you get the call in static method you can start a thread executing your tasks.
Note: Don't forget to release all the resources(threads etc.) in the service as android won't do it for you.
If your activity has finished then on task execution complete you can use stopSelf()
for the service and release all the resources.
you can try IntentService if it meets your need. Check this for more details.
IntentService might help, if you need to process requests one at a time. They are automatically queued to a worker thread.
Android library Goro might help.
It allows you to organize tasks in multiple queues and run them in service context.
By default it uses the same threads pool that is used in AsyncTask
to actually execute tasks.
精彩评论