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

天大地大妈咪最大 提交于 2019-12-05 02:05:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!