2012-11-13 15 views
7

This to znany, irytujący, 2-letni błąd Androida.Service.startForeground() generuje wyjątek NullPointerException po uruchomieniu z ServiceTestCase

Moje pytanie brzmi: czy ktoś zna jakieś obejście tego problemu, oprócz modyfikowania kodu źródłowego Androida i kompilowania go ponownie?

Oto mój kod dla dobra realizacji:

Moja metoda usługi podklasa że podnosi NPE:

/** Shows notification of started service */ 
private void doStartForeground() { 

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

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

Nazywa się to z onCreate() metody ręcznego.

A metoda badania 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); 
} 

Ślad stosu:

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) 

Usługa uruchamia się poprawnie i działa dobrze, gdy nie jest prowadzony przez JUnit Android.

Odpowiedz

6

I w końcu skończyło się dodanie nowego pola statycznego w mojej służbie:

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

i sprawdź to w metodzie onCreate():

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

Potem ustawić tę flagę z JUnit na setUp():

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

Niezbyt eleganckie rozwiązanie, ale usuwa mnie z blokady.

+1

Okropne! Thx za znalezienie tego. Problem można znaleźć na forum ADT tutaj: https://code.google.com/p/android/issues/detail?id=12122 – Snicolas

+1

Tak, widziałem to (link jest w pytaniu). Teraz ma 3 lata i liczy ... – m0skit0

+0

Zostało to zaznaczone jako przestarzałe, chociaż nie jestem pewien dlaczego. – Xiao

Powiązane problemy