How to get data from service to activity

In my Service class I wrote this

private static void sendMessageToActivity(Location l, String msg) {
    Intent intent = new Intent("GPSLocationUpdates");
    // You can also include some extra data.
    intent.putExtra("Status", msg);
    Bundle b = new Bundle();
    b.putParcelable("Location", l);
    intent.putExtra("Location", b);
    LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}

and at the Activity side we have to receive this Broadcast message

LocalBroadcastManager.getInstance(getActivity()).registerReceiver(
            mMessageReceiver, new IntentFilter("GPSLocationUpdates"));

By this way you can send message to an Activity. here mMessageReceiver is the class in that class you will perform what ever you want....

in my code I did this....

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Get extra data included in the Intent
        String message = intent.getStringExtra("Status");
        Bundle b = intent.getBundleExtra("Location");
        lastKnownLoc = (Location) b.getParcelable("Location");
        if (lastKnownLoc != null) {
            tvLatitude.setText(String.valueOf(lastKnownLoc.getLatitude()));
            tvLongitude
                    .setText(String.valueOf(lastKnownLoc.getLongitude()));
            tvAccuracy.setText(String.valueOf(lastKnownLoc.getAccuracy()));
            tvTimestamp.setText((new Date(lastKnownLoc.getTime())
                    .toString()));
            tvProvider.setText(lastKnownLoc.getProvider());
        }
        tvStatus.setText(message);
        // Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
    }
};

How to send data to Activity from IntentService ?

You don't need to bind a service if the service is meant for one way communication. For such cases using IntentService + BroadcastReceiver is quite easy.

Example:

You have a BackgroundService which calculates signal strength and sends back the data to Activity every second. And the Activity shows data in a GraphView.

How to do that?

enter image description here

Send data from Service

public class TrackWifiService extends IntentService {

    public TrackWifiService() {
        super("wifiService");
    }

    protected void onHandleIntent(@Nullable Intent intent) {

        sendDataToActivity()
    }

   private void sendDataToActivity()
   {
        Intent sendLevel = new Intent();
        sendLevel.setAction("GET_SIGNAL_STRENGTH");
        sendLevel.putExtra( "LEVEL_DATA","Strength_Value");
        sendBroadcast(sendLevel);

   }


}

Receive data from Service
For this, your Activity should register with a BroadcastReceiver

public class TrackWifiActivity extends AppCompatActivity {

   WifiLevelReceiver receiver;

   @Override
   public void onCreate(Bundle savedInstanceState)
   {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.track_wifi_activity_layout);
      receiver = new WifiLevelReceiver();
      registerReceiver(receiver, new IntentFilter("GET_SIGNAL_STRENGTH"));  //<----Register
   }


   @Override
   public void onStop()
   {
       super.onStop();
       unregisterReceiver(receiver);           //<-- Unregister to avoid memoryleak
   }

   class WifiLevelReceiver extends BroadcastReceiver {

       @Override
       public void onReceive(Context context, Intent intent) {

           if(intent.getAction().equals("GET_SIGNAL_STRENGTH"))
           {
              int level = intent.getIntExtra("LEVEL_DATA",0);

              // Show it in GraphView
           }
       }

   }

}

Note:

If you want to use LocalBroadcastReceiver instead of a BroadcastReceiver. You can just see check out How to convert BroadCastReceiver to LocalBroadcastReceiver

Relevant Links

See Full project
What is an IntentService?
Difference between Bound and Unbound Services


A good way to have it is using Handler. Create a innerClass in your activity that extends Handler and Override the handleMessage method.

Then, in your ServiceReceiver class, create a handler variable and a constructor like:

public ServiceReceiver(Handler handler){
   this.handler = handler;
}

So, in your activity, create your custom handler and pass it to your service. So, when you wants to put some data to your activity, you can put handler.sendMessage() in your Service (it will call handleMessage of your innerClass).

Tags:

Android