Android Service在测试工程中使用的注意事项
来源:互联网 发布:兄贵pat it 编辑:程序博客网 时间:2024/05/01 06:28
做单元测试时需要在测试工程里开一个http service,使用intent调起时却发现service怎么都起不来,代码如下:
看出错误在哪了吗?
答案:错误在context那里。
android的测试工程与被测工程关系非常密切,比如测试工程可以直接使用被测工程的各种权限而无需自己声明等。这里我犯的错误就是,我以为任何一个context实例都可以发送正确的intent,而不必区分测试工程还是被测工程。
Context之所以叫“上下文”,是因为它可以标志当前的环境,给各个参数提供一个背景。
这么说还是太抽象了,举个例子:
这是在AndroidManifest.xml文件中对一个service的声明。如果我使用上面的代码去startService,程序会去哪里找这个service呢?
事实证明它会去com.sg.sledog包里找这个service,因为这里使用了targetContext,也就是被测工程com.sg.sledog的context,在这个上下文里,涉及的一切intent、service等都被认为是com.sg.sledog中的。
所以service起不来,因为它根本就不在com.sg.sledog包里。
正确的做法是:
使用测试工程的context。
希望自己通过这次总结,能长点记性,以后不要再犯类似的错误
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
- Android Service在测试工程中使用的注意事项
- 在Android中使用Junit测试注意事项
- CppUnit测试框架在VC2008中使用的注意事项
- service中使用Toast.makeText的注意事项
- [笔记] Android Service 使用注意事项
- 使用Android Junit进行测试的注意事项
- SQLite在Android中使用注意事项
- Android在application中使用SharedPreference注意事项
- 使用XFire+Spring构建Web Service------测试工程在myeclipse的默认工作目录下的webservicetesthellworld
- 在多媒体会议室工程中信号传输设备连接的注意事项
- VS2010在使用win32工程时的注意事项
- android中Service的启动,停止,绑定的注意事项
- Android中service的使用
- Android中Service的使用
- Android中Service的使用
- 举例说明如何在android中使用Service
- [Android] 在Service中使用Toast
- android 在service中使用toast
- POJ 2299 Ultra-QuickSort(线段树+离散化)
- 设计模式六大原则(3):依赖倒置原则
- Effective Objective-C(第47-52条)系统架构,foundation、for-in、NSTimer
- hdu4845 状态压缩BFS
- 30天自制操作系统之第13天 定时器(2)
- Android Service在测试工程中使用的注意事项
- 要想快,先慢下来
- 使用aireplay-ng时报错“mon0 is on channel ×, but the AP uses channel ×”
- Ubuntu中解决解压zip文件中文乱码问题
- Struts2源码试读1-filter
- 【奇偶剪枝】HDU 1010 Tempter of the Bone
- memcpy的自定义实现的源代码
- hdu oj 2544 最短路(最短路径)
- nyoj 107