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

£可爱£侵袭症+ 提交于 2019-12-03 16:31:23

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.

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