kata32
kata32

Reputation: 35

Android share location data between activities

I have an app with two activity A and B (a google map), both need to periodically receive GPS location. I need that going from activity A to B and back app continues to retrieve the GPS position without interruption. To solve this problem I thought to two ways:

The first is to use a service that starts when app start and continuously retrieve GPS position and somehow notify both activities about new data, then, when the app finish it stop retrieving position.

The second way is to use the fragments, I have only one activity that continuously retrieve GPS position, then I have two fragments that show A and B content and somehow use the position data received from the activity.

When I say "somehow" I want to say that I don't know how :-)

Do you have suggestions on how to implement these two approaches or can you suggest better approaches?

Upvotes: 0

Views: 625

Answers (1)

blackkara
blackkara

Reputation: 5052

#1 Whenever location changed, send intent and receive it where you want

 LocalBroadcastManager mLocalBroadcastManager;

 @Override
 public void onLocationChanged(Location location) {
     Intent intent = new Intent();
     intent.putExtra("com.exmaple.sample", location);
     mLocalBroadcastManager.sendBroadcast(intent);
 }

#2 Whenever location changed, send intent and receive it where you want (same with 1)

@Override
public void onLocationChanged(Location location) {
    Intent intent = new Intent();
    intent.putExtra("com.exmaple.sample", location);
    sendBroadcast(intent);
}

#3 Or, pass a pending intent only one time, then receive locations

Intent intent = new Intent(mContext, YourBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 1, intent, 0);

mLocManager = (LocationManager)getSystemService(LOCATION_SERVICE);
mLocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, pendingIntent);

#4 Make a static variable, then poll it from an activity periodically. Note that, you should optimize polling frequency because it's not guaranteed getting fresh location. This is maybe be bad approach but it could be worth it for your scenario

public static Location sLastLocation;

@Override
public void onLocationChanged(Location location) {
    sLastLocation = location;
}

#5 Use event bus, link

Upvotes: 1

Related Questions