2012-11-13 29 views
7

This是一個已知的煩人的2歲Android錯誤。Service.startForeground()在使用ServiceTestCase運行時拋出NullPointerException

我的問題是,除了修改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的運行工作正常。

回答

6

我終於結束了在我的服務增加新的靜態字段:

/** 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; 
} 

不是最優雅的解決方案,但讓我走出封鎖。

+1

太糟糕了! Thx找到這個。這個問題在ADT論壇中引用:https://code.google.com/p/android/issues/detail?id=12122 – Snicolas

+1

是的,我看到了(鏈接在問題中)。它現在3歲了,正在計數... – m0skit0

+0

它被標記爲過時,但我不知道爲什麼。 – Xiao

相關問題