android启动服务时,ui线程是否需要去等待才能启动?

When starting a service in android, does the ui thread need to go to wait in order for it to start?

我在为 activity 编写测试时遇到问题,这让我想知道这个问题。我正在使用 ActivityInstrumentationTestCase2 并且我的 activity 在单击按钮时使用 startService 将意图发送到服务并且它工作正常。 (我的服务是 singelton,所以我可以知道它是否 运行)
在测试时,我正在执行以下操作:

  1. 断言服务不是 运行。
  2. 发送启动服务的意图(或按下按钮都试过)
  3. 等待服务启动并断言它是 运行

听起来很简单,但是当我尝试使用 Thread.sleep 等待时,服务不会启动,当我尝试忙等待时也是如此。所以我假设它需要完成 testMethod 才能启动服务,我做了以下设计:

Thread helper;

@Override
tearDown() {
    if (helper) join helper
    super.tearDown
}

testMethod() {
    assert stuff
    send intent
    start helper
    finish
}

helperMethod() {
    wait for service to start
    assert stuff
}

这确实有效,我的猜测是它让主线程完成 testMethod,然后处理意图并完成我的测试。这种行为看起来很奇怪,因为我希望服务会立即启动,因为它在同一个线程上,或者休眠足够长的时间会让服务启动。所以有人知道服务启动的条件是什么,什么时候启动?

服务在主线程上 运行。因此,如果您调用 Thread.sleep(),您的服务将在时间结束前启动。

来自服务文档http://developer.android.com/reference/android/app/Service.html

Note that services, like other application objects, run in the main thread of their hosting process. This means that, if your service is going to do any CPU intensive (such as MP3 playback) or blocking (such as networking) operations, it should spawn its own thread in which to do that work.