0

I want to get the current GPS coordinates using the GoogleApiClient as the LocationClient is now deprecated. But as I have more than one activity using the client, I don't want to repeatedly write an inner class for each activity.

But when I write an external class GPS defining the localization functionality, I cannot give any feedback from onLocationChanged(Location location) to the activities, which call the class GPS. How is this usually done? How can I access the location object from within the calling activity? Or is this only possible with an inner class?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Peder
  • 345
  • 1
  • 4
  • 14

1 Answers1

1

I have written an app which uses geolocation accross most of its activities. A solution I have chosen to serve all my clients (e.g: activities, dialogs, or even other apps) was to write a Service wrapping this logic of geolocation so I could bind/unbind from it as the user navigates between activities.

This also allowed me to keep the geolocation client up even when the user left all of the app activities, making it possible to notify him asynchronously of particular events happening nearby his location.

Your location logic will be located in one place in your project, and with a little bit of work abstracting away the kind of location provider you are using, you can test your app in a much more thorough way by changing the location provider with your own.

Halim Qarroum
  • 13,985
  • 4
  • 46
  • 71
  • Okay, my `GPS` class now extends Service, the service is registered in the Manifest.xml and I successfully started the service from within the activity. But how does the activity get feedback from the service? (I have never used services before.) – Peder Nov 02 '14 at 13:45
  • You must manage the lifecycle of your service and binding/unbinding to it from your activities. You can find a pretty straightforward way to manage services here : http://www.vogella.com/tutorials/AndroidServices/article.html. – Halim Qarroum Nov 02 '14 at 13:58
  • Basically you must define a binder interface, which will describe the methods exposed by your service (e.g: setOnLocationChange). And use the `Service` binding facilities to connect to it asynchronously. – Halim Qarroum Nov 02 '14 at 14:01
  • This is more complicated than I hoped. I finally got a `BroadcastReceiver` running which reacts to a broadcast sent by the `Service`. Thank you so far. – Peder Nov 02 '14 at 16:43