首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当使用ServiceTestCase运行时,Service.startForeground()抛出NullPointerException

当使用ServiceTestCase运行时,Service.startForeground()抛出NullPointerException
EN

Stack Overflow用户
提问于 2012-11-13 17:38:45
回答 1查看 2.1K关注 0票数 8

This是一个已有2年历史的令人讨厌的安卓bug。

我的问题是,除了修改Android源代码并重新编译之外,有没有人知道解决这个问题的办法?

为了完整起见,我的代码如下:

我的引发NPE的Service子类方法:

代码语言:javascript
复制
/** Shows notification of started service */
private void doStartForeground() {

    // Prepare notification
    final NotificationHelper nh = doNotification("Service started");

    // Start foreground
    startForeground(nh.getNotificationId(), nh.getNotification());
}

这是从onCreate()方法覆盖中调用的。

和JUnit测试方法:

代码语言:javascript
复制
public void test1() throws InterruptedException {
    assertTrue(context != null);
    final Intent service = new Intent();
    service.setComponent(new ComponentName(CoreService.PACKAGE_NAME,
        CoreService.SERVICE_FULL_NAME));
    IBinder binder = bindService(service);
    assertTrue(binder != null);
}

堆栈跟踪:

代码语言:javascript
复制
java.lang.NullPointerException
at android.app.Service.startForeground(Service.java:631)
at com.blablabla.android.core.CoreService.doStartForeground(CoreService.java:82)
at com.blablabla.android.core.CoreService.onCreate(CoreService.java:149)
at android.test.ServiceTestCase.bindService(ServiceTestCase.java:234)
at com.blablabla.android.core.test.MainTest.test1(MainTest.java:37)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:537)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1551)

该服务正确启动,并且在不通过安卓的JUnit运行时工作正常。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-11-13 19:07:16

我最终在我的服务中添加了一个新的静态字段:

代码语言:javascript
复制
/** JUNIT - this is for testing purposes only */
public static boolean isJUnit = false;

并在onCreate()方法中检查它:

代码语言:javascript
复制
// Start the service as foreground (Android should not kill this
// service)
if (!isJUnit) {
    doStartForeground();
}

然后,我从JUnit的setUp()设置了这个标志

代码语言:javascript
复制
@Override
protected void setUp() throws Exception {
    super.setUp();
    // More setup
    MyServiceClass.isJUnit = true;
}

不是最优雅的解决方案,但让我走出了封锁。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13358386

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档