在Android官方Aidl文档中,IPC客户端示例使用目标“RemoteService.class”明确声明一个intent。但是,当服务器和客户端不在同一个包中时,如果没有设置依赖关系,客户端不应该知道什么是“RemoteService”。该示例如何工作?
ref:https://developer.android.com/guide/components/aidl.html
我搜索了几个工作示例,并使用Action而不是远程服务类对象设置intent。
在Android文档中,
Intent intent = new Intent(Binding.this, RemoteService.class);
intent.setAction(IRemoteService.class.getName());
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
目前,我希望将其修改为:
Intent intent = new Intent("<remote-service-intent-filter-in-androidmanifest>");
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
您位于正确的路径上,但如果您在清单中添加了intent操作,那么您还应该在绑定服务时提及包名称。
intent.setPackage("<remote service package name>");
警告:为确保您的应用程序安全,请始终在启动服务时使用明确的意图,并且不要为您的服务声明意图过滤器。使用隐式意图启动服务存在安全隐患,因为您无法确定响应意图的服务,并且用户无法查看启动哪个服务。从Android 5.0(API级别21)开始,如果使用隐式intent调用bindService(),系统将抛出异常。 https://developer.android.com/guide/components/services
Snipplet:以下是我使用setClassName API连接到不同应用程序上的远程服务的方法。
注意:此方法不需要清单文件中的intent操作。
在客户活动。
/**
* Init Service
*/
private void initService() {
if (mSampleService == null) {
Intent i = new Intent();
// set intent action
i.setAction("com.hardian.sample.aidl.ISampleService");
// mention package name with service's canaonical name
i.setClassName("com.hardian.sample", "com.hardian.sample.aidl.SampleAidlService");
// binding to a remote service
bindService(i, mSampleServiceConnection, Service.BIND_AUTO_CREATE);
}
}
在服务
/**
* {@inheritDoc}
*/
@Override
public IBinder onBind(Intent intent) {
Log.d(TAG, "onBind called");
if (ISampleService.class.getName().equals(intent.getAction())) {
return mSampleServiceBinder;
}
return null;
}