Should you connect and disconnect to Google Play Services in each activity?
Asked Answered
M

1

4

I am writing an application which needs a connected location client in all the activities. How do the manage the state of the client?

I want to call the mLocationClient.connect() only once to avoid hassle, and should be able to remove location updates / disconnect when the application stops.

How do I keep the location client connected across all activities, assuming I have connected to it in the splash screen Activity?

Another question that arises here is, when I resume the paused application (not recreation), the app won't start with the splash screen. How do I maintain the connection in this case?

Thanks in advance.

Moise answered 16/6, 2014 at 1:1 Comment(0)
L
4

What you need is a bound service: these services only live while a client (like one of your activities) is connected to it. This allows you to have a shared state (a single connected location client) while still ensuring that you connect/disconnect appropriately.

In this situation, any location aware activity would bind to the service. When the first activity (say, your splash screen activity) binds to the service, the service would start and connect to Google Play Services. Your service's Binder would then give access to its LocationClient to any connected activities. As you move between activities, each would bind to the service in turn and be able to get the current location data and each would as they get destroyed.

When the user exits your application (i.e., the last activity is destroyed), then the service would automatically stop itself, allowing you to disconnect from Google Play Services.

As long as you bind to the service from every activity that needs location data, it doesn't matter which activity starts the service initially: the service would just connect if needed.

Leisure answered 16/6, 2014 at 1:16 Comment(3)
Thanks a lot for this insight. I will try to follow your method, and see if it helps my case.Moise
I realized this is the way to go, but I am having trouble figuring the right way to do it. Because connecting to googleplayservices, and fetching the location has a small delay, so I am thinking I need to broadcast the location once its available from the service. Is there some reference which you can suggest ?Moise
One easy way is for your Binder to offer registerLocationListener and unregisterLocationListener methods so that your Service can send locations as they get them to any attached clients (just make sure to unregister before you unbind from the service).Leisure

© 2022 - 2024 — McMap. All rights reserved.