Android send data from service to activity

www.laut‮rut‬i.com
Android send data from service to activity

service class

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

sendMessageToActivity(location, "location");

activity

LocalBroadcastManager.getInstance(context).registerReceiver(
                mMessageReceiver, new IntentFilter("GPSLocationUpdates"));
// define the mMessageReceiver :
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");
            Location lastKnownLoc = (Location) b.getParcelable("Location");
            if (lastKnownLoc != null) {
                latitude=lastKnownLoc.getLatitude();
                longitude=lastKnownLoc.getLongitude();
                Log.e("TAG", "Fragments Maps: "+ lastKnownLoc.getLatitude() + "\n longitude="+lastKnownLoc.getLongitude() );
            }
        }
    };
Created Time:2017-10-08 20:48:29  Author:lautturi