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

前端之家收集整理的这篇文章主要介绍了android – Service.startForeground()在使用ServiceTestCase运行时抛出NullPointerException前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
This是一个已知的令人烦恼的2岁Android漏洞.

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

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

提升NPE的My Service子类方法

  1. /** Shows notification of started service */
  2. private void doStartForeground() {
  3.  
  4. // Prepare notification
  5. final NotificationHelper nh = doNotification("Service started");
  6.  
  7. // Start foreground
  8. startForeground(nh.getNotificationId(),nh.getNotification());
  9. }

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

和JUnit测试方法

  1. public void test1() throws InterruptedException {
  2. assertTrue(context != null);
  3. final Intent service = new Intent();
  4. service.setComponent(new ComponentName(CoreService.PACKAGE_NAME,CoreService.SERVICE_FULL_NAME));
  5. IBinder binder = bindService(service);
  6. assertTrue(binder != null);
  7. }

堆栈跟踪:

  1. java.lang.NullPointerException
  2. at android.app.Service.startForeground(Service.java:631)
  3. at com.blablabla.android.core.CoreService.doStartForeground(CoreService.java:82)
  4. at com.blablabla.android.core.CoreService.onCreate(CoreService.java:149)
  5. at android.test.ServiceTestCase.bindService(ServiceTestCase.java:234)
  6. at com.blablabla.android.core.test.MainTest.test1(MainTest.java:37)
  7. at java.lang.reflect.Method.invokeNative(Native Method)
  8. at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
  9. at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
  10. at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:537)
  11. at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1551)

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

解决方法

我终于在我的服务中添加了一个新的静态字段:
  1. /** JUNIT - this is for testing purposes only */
  2. public static boolean isJUnit = false;

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

  1. // Start the service as foreground (Android should not kill this
  2. // service)
  3. if (!isJUnit) {
  4. doStartForeground();
  5. }

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

  1. @Override
  2. protected void setUp() throws Exception {
  3. super.setUp();
  4. // More setup
  5. MyServiceClass.isJUnit = true;
  6. }

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

猜你在找的Android相关文章