2012-11-13 10 views
7

Thisは、厄介な2年前のAndroidの既知のバグです。ServiceTestCaseでService.startForeground()を実行すると、NullPointerExceptionがスローされる

私の質問は、誰もがこの問題の回避策を知っていますか?Androidソースコードを変更してもう一度コンパイルしてください。 NPEを上げる

私のサービス・サブクラスのメソッド::これはonCreate()メソッドのオーバーライドから

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

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

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

と呼ばれる

はここで完成のために私のコードです。

と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()方法でそれを確認します:

答えて

6

は、私は最終的に私のサービスに新しい静的フィールドを追加することになった

:私はJUnitのの setUp()からこのフラグを設定すると
// Start the service as foreground (Android should not kill this 
// service) 
if (!isJUnit) { 
    doStartForeground(); 
} 

@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

関連する問題