8

これは既知の迷惑な 2 年前の Android バグです。

私の質問は、Android ソース コードを変更して再度コンパイルする以外に、この問題の回避策を知っている人はいますか?

完成させるための私のコードは次のとおりです。

NPE を発生させる My Service サブクラス メソッド:

/** 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 を介して実行しない場合、サービスは正しく開始され、正常に動作します。

4

1 に答える 1

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

最もエレガントなソリューションではありませんが、封鎖から抜け出します。

于 2012-11-13T11:07:16.227 に答える