我正在尝试测试与我定义的服务的外部绑定。遵循我用于仪器测试的课程:
@Rule
public final ServiceTestRule serviceRule = new ServiceTestRule();
@Test
public void testWithBoundService() throws TimeoutException, RemoteException {
IMyInterface iMyInterface;
Intent serviceIntent =
new Intent(ApplicationProvider.getApplicationContext(),
MyService.class);
IBinder binder = serviceRule.bindService(serviceIntent);
assertNotNull(binder);
iMyInterface = IMyInterface.Stub.asInterface(binder);
assertTrue(iMyInterface.retrieveValue(new Attribute()).getValues().get(0).equals("home"));
}
@Test
public void testWithBoundServiceExternal() throws TimeoutException, RemoteException {
IMyInterface iMyInterface;
Intent serviceIntent = new Intent();
serviceIntent.setClassName("a.b.c.d", "a.b.c.d.MyService");
IBinder binder = serviceRule.bindService(serviceIntent);
assertNotNull(binder);
iMyInterface = IMyInterface.Stub.asInterface(binder);
boolean reachedHere = false;
assertTrue(iMyInterface.retrieveValue(new Attribute()).getValues().get(0).equals("home"));
}
第一个测试功能运行没有任何错误,第二个失败,并显示以下消息:
绑定服务失败!清单中声明了您的服务吗?
服务在a.b.c.d包中定义,与Aidl接口相同,而instrumentedTest在a.b.c.e包中运行
答案 0 :(得分:0)
几分钟后,我意识到清单有一个不同的程序包,并且为了调用服务,您应该使用清单的程序包。因此,假设您在标签中拥有一个属性package =“ a.b.c.f”,以便调用外部服务,则应使用:
serviceIntent.setClassName("a.b.c.f", "a.b.c.d.MyService")