Question

I am making an app that has to use user's current location in many activities. I don't really want to implement a location client in every activity. What's the best way to use the current location in my app? Probably a background service? And if so, how can I use that? Any example?

Was it helpful?

Solution

First, the answer by "Hemant Chand Dungriyal" is incorrect. The class is inherited from Service, but does not use any features provided by Service components, so basically it's just a regular class, you might as well remove the "extends Service" part! (apparently I don't have enoug reputation to put comment!)

Overall, I think it's better for each client to manage their own connection to LocationProvider service in android, this way they can request the location matching their needs. For example if an activity needs only a rough location vs. another one which needs last known location from system vs. another one which needs a fine location, you won't waste system resources by giving fine location to all of them.

But if you know that the fine location is needed at all parts of your app, then using Service is one option. But then you should manage the lifecycle of the service (whether you want it to be bound service, or started service?, when to create and when to destroy it? etc.) Also you need to know when all activities are closed and it's safe to shutdown the service.

The alternative would be implementing the code in the application class. You can initialize when the first activity needs accessing it, and then when all activities are closed you can shut it down (again you need a mechanism to figure out if there are still visible activities who need to know the location).

For the implementation example, I am sure you can find quite a few, just google it.

OTHER TIPS

I recommend following this example using Google Play services and then extending the Activities that need locations from the resulting FragmentActivity: http://developer.android.com/training/location/receive-location-updates.html

If you are publishing outside of Play Store, you can use the older Location services in Android (or a library leveraging them) and doing so from the Application is feasible but a base Activity class is just as simple, makes for cleaner lifecycle management and compartmentalizes the location code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top