I’ve built an IntentService to collect location data in the background (with the user’s knowledge). It uses a PendingIntent to receive locations, rather than a LocationListener. I receive locations fine in the receiver.
But how do I pick up these locations from an Activity? Can I receive the location broadcasts directly, or do I need to send a new type of broadcast for activities to receive?
Service:
Intent activeIntent = new Intent(this, LocationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, activeIntent, PendingIntent.FLAG_UPDATE_CURRENT);
LocationManager locationManager = (LocationManager) (App.getInstance().getSystemService(Context.LOCATION_SERVICE));
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_TIME_CHANGE, LOCATION_DISTANCE_CHANGE, pendingIntent);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, LOCATION_TIME_CHANGE, LOCATION_DISTANCE_CHANGE, pendingIntent);
locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, LOCATION_TIME_CHANGE, LOCATION_DISTANCE_CHANGE, pendingIntent);
Receiver:
@Override
public void onReceive(Context context, Intent intent) {
Bundle b = intent.getExtras();
Location loc = (Location)b.get(android.location.LocationManager.KEY_LOCATION_CHANGED);
// TODO handle the location here
}
I would use the same broadcast event.
Define a more generic action for your intent.
Then, register
LocationReceiverin your Manifest with that action as the filter. This way you will always receive the broadcast in yourLocationReceiver.Finally, to get the broadcast in your Activities, register/unregister an anonymous broadcast receiver (again, with your action as a filter) in onResume/onPause.