In my Android application, I have a simple list view with adapter. There's a heavy query which is to fill the list view with data. So I put it to an IntentService that runs in another thread.
The IntentService is normally running separately, on its own, just to query some data and insert it into the SQLite database.
But now I would like to have the following possibility:
- The activity starts the IntentService with startService().
- The IntentService does its heavy work.
- When the IntentService is finished, it should inform the activity about the result so that the activity can be refreshed to show the new data.
Is this possible? I read a lot of questions here on Stack Overflow on this topic. But in every question, there was another solution. So I want to ask you all: Which solution is the best for my purpose?
- Binding the IntentService to the Activity does not seem to be the best solution as there might be conflicts with configuration changes of the activity etc. Correct?
- This blog post suggests using AIDL with Parcelables - which sounds very complex to me. There is an easier way, isn't it?
- One could set up a broadcast receiver in the activity and fire this broadcast in the IntentService when it is finished.
- Some people say you should use createPendingResult() to pass a PendingIntent to the IntentService. If the IntentService finds that PendingIntent in its extras, it uses this to trigger off onActivityResult() in the Activity. Is this the way to choose?
When the IntentService completes, it should use LocalBroadcastManager to send an intent to any registered activity.
The IntentService will contain code like this:
The activity receiving the notification will contain code like this:
For more depth, see the blog post Using LocalBroadcastManager In Service To Activity Communications.
I would suggest using a Broadcast Receiver in the The Activity waiting for the result. Your Service would just use
sendBroadcast
with a customIntent
.I think the event bus is the way to go. Simple and effective interprocess communication.
None of the other answers references the official android documentation
https://developer.android.com/training/run-background-service/report-status.html
that states clearly that for the Activity-IntentService communication "The recommended way to send and receive status is to use a LocalBroadcastManager, which limits broadcast Intent objects to components in your own app"!
As an example, I use a ResultReceiver to call
notifyDataSetChanged()
on the adapter of myActivity
(which extendsListActivity
). It can be adapted to do whatever you need.ResultReceiver code:
MyActivity code:
IntentService code: