Feras
Feras

Reputation: 2184

Android service and asynctask communication

I have a problem trying to figure out the best way to complete a simple app following the Android best practises. Here is the scenario:

1) I have an activity where the user enters something, its then send to a background Service

2) The background service performs some checks on the input and spawns a new AsyncTask to process the input.

3) The asynctask updates a Status Hashmap in the service with its progress and status

4) There is an second activity that binds to the Service to display a list of currently running tasks from the service and their progresses. The idea is that even if this activity is closed the service will continue to run the tasks and when the activity is reopened the refreshed stats will be shown.

I have problems in 3 and 4. What is the best way to communicate to the Service from within the AsyncTask's onProgressUpdate method and at the same time update the listing activity if its opened, if its not opened its simpler, just update the service tracking maps and when the activity is opened it will read them and update.

Im not sure what is the standart approach to handle "Events" of that sort. Do you have to use a Broadcast listener and subscriber or its too much for this simple purpose?

Upvotes: 0

Views: 842

Answers (1)

Ani Fichadia
Ani Fichadia

Reputation: 277

If you want to communicate between the service and an activity, you could broadcast updates from the service within the AsyncTask.onProgressUpdate method (alternatively within the AsyncTask.onPostExecute(Result) method) and listen for the updates using a broadcast receiver within your activity.

Instead of me copying and pasting a lotta code, check out Vogella's tutorial on services, especially the exercise (7. Exercise: Using services and service communication), found here

www.vogella.com/tutorials/AndroidServices/article.html#tutorial_intentservice

Within the exercise, you're looking for the DownloadService.publishResults(...) method which sends out a broadcast from the service to whichever broadcastreceiver is listening for updates, and the use of the BroadcastReceiver in MainActivity, which handles the updates from the service.

Upvotes: 2

Related Questions