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