how does a service return result to an activity

You can use Pending Intent,Event Bus,Messenger or Broadcast Intents to get data from service back to activity/fragment and then perform some operation on the data.

My blog post covers all these approaches.


According to Google documentation, if your Activity and Service are within the same app, using a LocalBroadcastManager is preferable over sendBroadcast (intent) because the information sent does not go through the system which eliminates the risk of interception.

It's quite easy to use.

In your activity, create a BroadcastReceiver and dynamically add a listener in the onResume() method :

private BroadcastReceiver  bReceiver = new BroadcastReceiver(){

    @Override
    public void onReceive(Context context, Intent intent) {
        //put here whaterver you want your activity to do with the intent received
    }           
};

protected void onResume(){
    super.onResume();
    LocalBroadcastManager.getInstance(this).registerReceiver(bReceiver, new IntentFilter("message"));
}

protected void onPause (){
    super.onPause();
 LocalBroadcastManager.getInstance(this).unregisterReceiver(bReceiver);
}

And in your service, you get an instance of LocalBroadcastManager and use it to send an intent. I usually put it in its own method like this :

private void sendBroadcast (boolean success){
    Intent intent = new Intent ("message"); //put the same message as in the filter you used in the activity when registering the receiver
    intent.putExtra("success", success);
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}

If you need return various types of data, such as user-defined class, you may try bindService and callback. This can avoid implement parcelable interface than sendBroadcast.

Please see the example in my post:

https://stackoverflow.com/a/22549709/2782538

And more, if you use IntentService, you could look into ResultReceiver. The details and sample could be found in this post:

Android: restful API service

Hope it helps.


Send a broadcast Intent with the data via sendBroadcast(), that the activity picks up with a BroadcastReceiver.

Here's an example of that: https://github.com/commonsguy/cw-android/tree/master/Service/WeatherAPI Doc: http://developer.android.com/reference/android/content/BroadcastReceiver.html