Android – Best way to implement LocationListener across multiple activities

The way that I would typically implement this requirement is using a bound Service implementation, like the one in the Local Service Sample in the SDK Documentation. Obviously you’re familiar with the advantage of the Service allowing you to create all the location code only once.

Accessing the Service through Bindings allows the Service to start and stop itself so it isn’t running when your application isn’t in the foreground (it will die as soon as no more Activities are bound). The key, IMO, to making this work well is to BIND the service in onStart() and UNBIND in onStop(), because those two calls overlap as you move from one Activity to another (Second Activity Starts before the First one Stops). This keeps the Service from dying when moving around inside the app, and only lets the service die when the entire application (or at least any part interested in location) leaves the foreground.

With Bindings, you don’t have to pass the Location data in a Broadcast, because the Activity can call methods directly on the Service to get the latest location. However, a Broadcast would still be advantageous as a method of indicating WHEN a new update is available…but this would just become a notifier to the listening Activity to call the getLocation() method on the Service.

My $0.02. Hope that Helps!

Leave a Comment