公平地说,我不是在测试该服务,而是使用服务作为我的测试类的一部分来测试蓝牙库。因此,我的测试类需要创建一个调用蓝牙库的服务。然后测试类需要绑定到该服务来执行测试。但是,尝试启动服务总是会出现以下错误,从而导致空指针异常
W/ActivityManager: Unable to start service Intent { cmp=com.example.androidhdpadapter.test/com.lampreynetworks.ahd.oxp.transport.BluetoothTestService } U=0: not found
现阶段测试类很简单:
package com.lampreynetworks.ahd.oxp.transport;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.rule.ServiceTestRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.concurrent.TimeoutException;
import static org.junit.Assert.fail;
@RunWith(AndroidJUnit4.class)
public class AndroidServiceBluetoothAdapterTests
{
private final static String TAG =
AndroidServiceBluetoothAdapterTests.class.getName();
@Rule
public final ServiceTestRule serviceRule = new ServiceTestRule();
@Test
public void testAndroidBluetoothAdapter() throws TimeoutException, InterruptedException
{
Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
Intent intent = new Intent(context, BluetoothTestService.class);
serviceRule.startService(intent);
Thread.sleep(12000);
IBinder binder = serviceRule.bindService(intent);
BluetoothTestService service = ((BluetoothTestService.TestManagerBinder) binder).getService();
serviceRule.unbindService();
}
}
有很多关于测试服务问题的帖子,我已经尝试了所有这些问题(弄乱 gradle.build 文件依赖项、androidx.test 和 android.support.test 之间的冲突等)。我也尝试过在没有 ServiceTestRule 的情况下以标准方式调用服务,但这可能会失败,因为没有用于指定服务的测试的 AndroidManifest(我不知道是否可以做到)。
也许无法使用 Androidx 的 ServiceTestRule,除非实际测试属于应用程序一部分的服务。在这里,我正在测试一个通常由服务调用的蓝牙库,并且此测试服务不是该库的一部分,而是仅存在于 androidTests 目录中。
我这样做的原因是 Android 的蓝牙有问题,在某些平台上,蓝牙会自发关闭然后重新启动。我的蓝牙库尝试从这次关闭中恢复。恢复有效,但是对于每次自发关闭和恢复,我都会遇到服务泄漏。这就是我试图在简化的框架而不是成熟的应用程序中解决的问题。
一旦你拥有了 机器人:单用户=“真” 在您的服务中,似乎您没有任何可能检测任何东西!