Android Service在测试工程中使用的注意事项

来源:互联网 发布:兄贵pat it 编辑:程序博客网 时间:2024/05/01 06:28
做单元测试时需要在测试工程里开一个http service,使用intent调起时却发现service怎么都起不来,代码如下:

context = getInstrumentation().getTargetContext();intent = new Intent(context, TestService.class);context.startService(intent); 

看出错误在哪了吗?


答案:错误在context那里。

android的测试工程与被测工程关系非常密切,比如测试工程可以直接使用被测工程的各种权限而无需自己声明等。这里我犯的错误就是,我以为任何一个context实例都可以发送正确的intent,而不必区分测试工程还是被测工程。

Context之所以叫“上下文”,是因为它可以标志当前的环境,给各个参数提供一个背景。

这么说还是太抽象了,举个例子:

      
  <service            android:name="com.sg.sledog.http.SledogWebService"            android:launchMode="singleTask" >            <intent-filter>                <action android:name="com.sg.sledog.http.SledogWebService" />            </intent-filter>        </service>


这是在AndroidManifest.xml文件中对一个service的声明。如果我使用上面的代码去startService,程序会去哪里找这个service呢?
事实证明它会去com.sg.sledog包里找这个service,因为这里使用了targetContext,也就是被测工程com.sg.sledog的context,在这个上下文里,涉及的一切intent、service等都被认为是com.sg.sledog中的。

所以service起不来,因为它根本就不在com.sg.sledog包里。

正确的做法是:


context = getInstrumentation().getContext();intent = new Intent(context, TestService.class);context.startService(intent); 

使用测试工程的context。


希望自己通过这次总结,能长点记性,以后不要再犯类似的错误
0 0