简体   繁体   English

如何在活动开始时等待服务

[英]How to wait for service on activity start

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. 我希望服务启动或在应用程序启动时获取它的当前实例,因此我将繁忙的等待放入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 另外,如果有更好的方法,请发布任何链接或指南,因为我在android开发人员网站上很困惑:P

thanks! 谢谢!

I used a singleton approach from this tip. 我从这篇技巧中使用了单例方法。

Don't do that. 不要那样做 Use bindService() and the local binding pattern instead, and you will be notified when the service is ready. 改用bindService()和本地绑定模式,服务准备就绪时会通知您。 You also get access to an API published by the service and can start using it once you are bound. 您还可以访问该服务发布的API,并且一旦绑定就可以开始使用它。

The problem is one of procedural vs. event-driven programming, android's UI being built on the later. 问题是程序驱动的编程与事件驱动的编程之一,Android的UI建立在以后。

onCreate is an event. onCreate是一个事件。 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. 从onCreate返回之前,您不会收到服务连接通知(即使它已经发生)。

Can you split your activity startup into two parts, the first done in onCreate and the second in response to the service connection? 您能否将活动启动分为两部分,第一部分在onCreate中完成,第二部分响应服务连接?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM