0

I have followed this tutorial and now I have a working activity with google map fragment.

I need to keep track on the location of my app's users - the fragment has a onLocationChanged method which fires when location is changed, and on that method I update My Database with the user's location, draw the user on the map and more stuff.

The only issue is - I want to also have a service that will always send updates to my database and update each user's location, also when the app is closed.

Should I put the onLocationChanged method in both the fragment and service somehow? because when the app is on the foreground, I also do more things on the onLocationChanged beside updating the database, like drawing the map etc.

Emzor
  • 1,380
  • 17
  • 28
Ofek Agmon
  • 5,040
  • 14
  • 57
  • 101

1 Answers1

0

Why not just have your service receive all location updates, and use LocalBroadcastManager to broadcast intents with the location updates to any fragment or activity that registers an internal BroadcastReceiver with the intent filter? Here is a tutorial on how to use LocalBroadcastManager. Also, here is an example of how I made my internal BroadcastReceivers:

static class InternalBroadCastReceiver extends BroadcastReceiver{

    MyFragment mMyFragment;

    public InternalBroadCastReceiver(MyFragment fragment){
        mMyFragment = fragment;
    }

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

        final MyFragment fragment = mMyFragment;

        if (fragment != null) {
            Location location = intent.getParcelableExtra("myLocation");

            //...  Do something with your location here, for example:
            fragment.updatemap(location);
        }
    }
}
Pablo Baxter
  • 2,144
  • 1
  • 17
  • 36