Issue
I have encountered a problem while writing tests for my activity which made me wonder about this issue. I'm using ActivityInstrumentationTestCase2 and my activity sends intents to the service using startService when a button is clicked and it works fine. (My service is a singelton so i can know if it is running)
When in testing I'm doing the following:
- assert service isn't running.
- send intent to start the service (or press the button tried both)
- wait for the service to start and assert it is running
sounds pretty simple but when i try to wait using Thread.sleep the service wont start, and same for when i try doing busy waiting. So i assumed it will need to finish the testMethod to start the service and i made the following design:
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
}
this actually works, my guess is that it lets the main thread to finish the testMethod and then the intents are handled and my test finishes. This behavior seems very odd as i would expect that the service will start immediately as it is on the same thread or sleeping for enough time will let the service start. So anyone knows what are the conditions for the service to start, and when it happens?
Solution
Services are running on the main thread. So if you call Thread.sleep() your service won't start until the time is up.
From the Service document 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.
Answered By - Hoan Nguyen
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.