如何等待活动开始时的服务
我正在制作一个应用程序,该应用程序具有与单个服务通信的活动,并用于启动、停止或更改该服务的设置。我使用了this技巧中的单例方法。
我的问题是忙碌等待对我不起作用,并且我无法将侦听器附加到服务,因为活动被阻止。我希望服务在应用程序启动时启动或获取其当前实例,因此我将忙等待放在 onCreate 中。我猜我这样做是非常错误的,那么我该如何正确地做到这一点呢?
另外,如果有更好的方法,请发布任何链接或指南,因为我在 Android 开发者网站上感到困惑:P
谢谢!
I am making an application that has Activity which communicates with a single service, and is used to start, stop or change settings of that service. I used a singleton approach from this tip.
My problem is that busy-waiting is not working for me and I can't attach a listener to the service because activity gets blocked. I want the service to start or get it's current instance at application start so I put the busy-waiting in onCreate. I'm guessing I'm doing this very wrong, so how do I do this appropriately?
Also if there is a better approach to this, please post any links or guides, cuz I'm getn confused on android developer site :P
thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要那样做。请改用
bindService()
和本地绑定模式,当服务准备就绪时您将收到通知。您还可以访问该服务发布的 API,并在绑定后即可开始使用它。Don't do that. Use
bindService()
and the local binding pattern instead, and you will be notified when the service is ready. You also get access to an API published by the service and can start using it once you are bound.问题是过程式编程与事件驱动式编程之一,android 的 UI 是建立在后者之上的。
onCreate 是一个事件。服务连接的通知也是一个事件。在从 onCreate 返回之前,您不会收到服务连接通知(即使已发生)。
您能否将 Activity 启动分为两部分,第一部分在 onCreate 中完成,第二部分在响应服务连接中完成?
The problem is one of procedural vs. event-driven programming, android's UI being built on the later.
onCreate is an event. Notification of a service connection is also an event. You won't be delivered the service connection notification (even though it's happened) until you return from onCreate.
Can you split your activity startup into two parts, the first done in onCreate and the second in response to the service connection?