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();
    }
};

Leave a Comment