从单例绑定服务 [英] Bind service from singleton

查看:148
本文介绍了从单例绑定服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个已启动的服务,该服务处理连接并保留对象数组.另一方面,我有一个单例应该绑定到该服务,以便获得该服务处理的对象之一.那么,如何从单例绑定服务?通过使用应用程序的上下文初始化单例时,绑定服务是一种好习惯吗?有更好的选择吗?

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?

提前谢谢!

推荐答案

这是一种非常好的方法.您的单身人士已初始化,并使用应用程序上下文绑定到服务.单例将保持绑定状态,直到托管您的单例的进程被Android杀死(或直到您有意解除绑定)为止.请注意,如果您有意解除绑定,那么如果您的应用在Android破坏托管进程之前再次启动(或者您需要破坏单身以便稍后重新初始化),则需要有意重新绑定.

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).

在Android杀死您的进程而用户返回到应用程序的情况下,您的单例将被重新创建并重新绑定到服务.

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.

这篇关于从单例绑定服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆