java - 客户端进程(在带有aidl的android IPC中)如何知道远程服务器类?
问题描述
在 Android 官方 Aidl 文档中,IPC 客户端示例使用目标“RemoteService.class”显式声明了一个意图。但是,当服务器和客户端不在同一个包中时,如果没有设置依赖项,客户端不应该知道什么是“RemoteService”。这个例子是如何工作的?
参考:https ://developer.android.com/guide/components/aidl.html
我搜索了几个工作示例,意图是使用 Action 而不是远程服务类对象设置的。
在 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.setPackage("<remote service package name>");
注意:为确保您的应用程序安全,请始终在启动服务时使用显式意图,并且不要为您的服务声明意图过滤器。使用隐式意图启动服务是一种安全隐患,因为您无法确定响应该意图的服务,并且用户无法看到哪个服务启动。从 Android 5.0(API 级别 21)开始,如果您使用隐式 Intent 调用 bindService(),系统将引发异常。 https://developer.android.com/guide/components/services
Snipplet:这是我使用 setClassName API 连接到不同应用程序上的远程服务的方法。
注意:这种方法不需要清单文件中的意图操作。
在客户活动中。
/**
* 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;
}
推荐阅读
- sql - 如何使其成为BCNF
- php - 仅当满足 php 变量条件时,如何显示我的选择选项值?
- r - 使用 par(mfrow()) 绘制固定数量的图形
- android - 使用 viewModelScope.launch 时如何获得返回结果?
- vue.js - 如何使用 Vue.js 在响应函数中运行方法
- powerbi - 枚举 Power M List 中的非 1 步
- html - 转换:翻译功能使徽标模糊
- flutter - 如何在颤动中加载主小部件之前显示加载小部件?
- java - 如果我的服务启动时间早于引用的一半,如何更新 OSGI @Reference 列表
- go - 如何在 Echo 框架中绑定复选框?