Search code examples
androidbackground-service

Background service to perform uploads


I have an application currently that uploads images to a server. To upload these images, I use an AsyncTask which works allright. It uploads the image, shows notifications for it along with the progress. For multiple images, separate async tasks are created. But I need something more:

  • Instead of creating multiple AsyncTasks, I would like to queue the uploads on the same thread.

I think a background Service is what I need. My question is can I use a Service to accomplish these tasks:

  • When the UploadActivity opens, it checks to see if the Service is running. If the Service is running, it updates the UI to show what images are currently being uploaded. (I maintain a SQLite database for the uploads, so if I can detect the service is running, I can pull the results from the table to see which files are in queue).
  • The UploadActivity contains a RecyclerView which shows the files which are not yet uploaded. Touching an item should also check if the Service is running. If the Service is not running, it should start the service, and queue the touched item for upload. If the Service is running, then it simply queues the file for upload.
  • The UploadActivity should constantly receive updates from the Service, so the user gets a view of the uploads progress ( this will be shown in the notification panel, but I need the progress and other details to be shown in the Activity as well).

The main roadblock for me is detecting if the service is running. Also, is it possible to let the Service know I have added another file to the queue (adding file to the queue is just an SQL insert into the table. The service should append the new file to the queue once the activity says a file has been added)

Edit:

Here is a pseudocode of what Im trying to achieve:

   Service service = new Service();
   If service.isRunning{
          service.itemAddedToQueueAndUpdateNotification()
   }else{
        service.start()
   }

And some callback like

    onServiceUpdateRecieved(){
              //Update UI
    }

Solution

  • You may use an Intent in order to broadcast either the new schedule (sent by activity, received by service) or the actual upload result (sent by service, received by activity, if active)