问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/24235474/should-you-connect-and-disconnect-to-google-play-services-in-each-activity