Bind service from singleton

社会主义新天地 提交于 2019-12-10 21:57:35

问题


I have a started service that handles a connection and that keep an array of objects. On the other hand, I have a singleton that should bind to that service in order to get one of the objects handled by the service. So, how could I bind the service from the singleton? Is it a good practice to bind the service when the singleton is initialized by using the application's context? Is there a better alternative?

Thanks in advance!


回答1:


This is a perfectly good way to do it. Your singleton gets initialized and binds to the service using application context. The singleton will stay bound until the process hosting your singleton is killed by Android (or until you intentionally unbind). Be aware that if you intentionally unbind then you will need to intentionally bind again if your app starts again before Android has destroyed the hosting process (or you'll need to destroy your singleton so it gets reinitialized later).

In the case where Android kills your process and the user returns to the app, your singleton will get recreated and will rebind to the service.



来源:https://stackoverflow.com/questions/35649033/bind-service-from-singleton

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