gpt4 book ai didi

android - Service.startForeground() 在使用 ServiceTestCase 运行时抛出 NullPointerException

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:57:56 25 4
gpt4 key购买 nike

This是一个已有 2 年历史的恼人 Android 错误。

我的问题是,除了修改 Android 源代码并重新编译之外,有人知道解决此问题的任何方法吗?

为了完成,这是我的代码:

引发 NPE 的服务子类方法:

/** 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 测试方法:

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);
}

堆栈跟踪:

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)

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

最佳答案

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

/** JUNIT - this is for testing purposes only */
public static boolean isJUnit = false;

并在 onCreate() 方法中检查:

// Start the service as foreground (Android should not kill this
// service)
if (!isJUnit) {
doStartForeground();
}

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

@Override
protected void setUp() throws Exception {
super.setUp();
// More setup
MyServiceClass.isJUnit = true;
}

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

关于android - Service.startForeground() 在使用 ServiceTestCase 运行时抛出 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13358386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com