-
I have a class that implements fileuploader service. Activites bind to it and supply it a list of files to be uploaded, and then unbind immediately. The files are then uploaded one-by-one by the service in a background thread(asynctask).
-
I start this service in my dashboard actvity using startService(), so that it keeps running until specifically stopService() is called.
-
Now, my question is when do I stop this service?
Basically I need to check two conditions: 1: all files are uploaded; 2: app has exited.
Also, to exit the App, user has to press back button on dashboard activity.
I could have overrided back button press and queriesd the service whether any files are left, but I dont want to use that method.
Any suggestions?
I would recommend then using
startService()rather thanbindService().This seems like a much better fit for
startService()and anIntentService(or aWakefulIntentServiceperhaps, if you are concerned about the device falling asleep during uploads).This would not be needed if you used
startService()for sending over the work.Ideally, the service would shut itself down, like
IntentServicedoes. After all, only the service knows when the service is done.When you have no more work to do.
IntentServicedoes this automatically. If you really want to maintain your own thread pool for doing the work, then when your work queue is empty and all threads are done, callstopSelf()from within the service.Yes.
No. Your UI should not care whether the service is running or not running. The service should take care of itself.
Users are welcome to leave your app however they please: BACK, HOME, RECENTS, a
Notification, an incoming phone call, etc.Use an
IntentService. Send over the jobs to be uploaded via calls tostartService(), packaging all needed data into theIntentused withstartService()(e.g., extras). Do your upload work inonHandleIntent(). If desired, useLocalBroadcastManagerto let activities in your app know about the upload status, so they can reflect that in their UI if they so choose.IntentServicewill handle stopping itself when its work queue empties.