aidl的使用简介
来源:互联网 发布:华为整体网络解决方案 编辑:程序博客网 时间:2024/05/24 03:54
转载请注明出处 http://blog.csdn.net/u012308861/article/details/50717977 IrisPanda的博客
在Android系统中,有很多进程,一个进程中包含若干个Activity和Service。那么不同进程里的Activity和Service怎么通信呢?Android提供了一种解决方案,也就是Binder。Binder就是用来进程间通信的。
为了方便使用Binder进行跨进程通信,android提供了aidl这种解决方法。本文主要介绍aidl的使用。
客户端代码:
private ISizeAidlInterface sizeInterface;private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { sizeInterface = ISizeInterface.Stub.asInterface(service); //asInterface根据是否跨进程来返回本地对象或代理对象。 } @Override public void onServiceDisconnected(ComponentName name) { } };//启动Serviceprivate void bind() { Intent intent = new Intent(this, SizeService.class); bindService(intent, connection, BIND_AUTO_CREATE);}
那么这个Ibinder对象是怎么来的呢?传入在这里:
public class SizeService extends Service{ private SizeImpl binder = new SizeImpl();//binder具体服务端实现类 @Nullable @Override public IBinder onBind(Intent intent) { return binder;//这里就是onServiceConnected接受到的Ibinder! }}
真正的Binder对象,实现了需要通信的接口
public class SizeImpl extends ISizeAidlInterface.Stub { int size; @Override public void setSize(int size) throws RemoteException { this.size = size; } @Override public int getSize() throws RemoteException { return size; }}
ISizeAidlInterface.aidl文件:
interface ISizeAidlInterface{ void setSize(int size); int getSize();}
上一张潦草的这几个类的关系图(只可意会)
可以看到他们的关系几乎是线性的,其中有几个关键点需要知道:
1、首先我们会自己写一个aidl的类,就是图中的interface ISizeInterface类,
然后编译后会自动生成一个同名的java文件。这个过程就是图中标号为0的过程,这个文件先在这放着。
2、onServiceConnected接受到的Ibinder对象到底是什么?
根据关系图,很清晰明了,Ibinder首先是在Service中返回的SizeImpl对象,SizeImpl就是Binder的具体实现类。看到Stub类了吧,它是aidl自动生成的,既是一个Binder,又实现了ISizeInterface接口。好吧,我们在客户端中想要的就是它!所以它本质上就是我们想要的ISizeInterface类。但是这里不能强转类型,因为我们现在是在跨进程调用,所以需要用到代码:
ISizeAidlInterface sizeInterface =ISizeInterface.Stub.asInterface(service);
通过asInterface方法,可以判断service是不是跨进程,从而返回本地的IBinder对象,或者是可供远程调用的Proxy对象。
下一篇分析一下aidl自动生成的java代码。
- aidl的使用简介
- aidl 使用案例简介
- AIDL的使用
- android aidl的使用
- Android AIDL的使用
- android AIDL的使用
- AIDL的简单使用
- AIDL的使用
- AIDL Service 的使用
- AIDL的使用
- aidl的简单使用
- AIDL的使用
- 简单明了的AIDL使用
- 浅析AIDL的使用
- AIDL的使用
- AIDL的使用
- AIDL的使用步骤
- AIDL简单的使用
- React复合组件
- logback.xml 常用配置详解
- NSCondition和NSConditionLock
- FastDFS+Nginx安装配置笔记
- 如何提升销售培训工作的有效性?
- aidl的使用简介
- HDU 1203 I NEED A OFFER!
- iOS AppStore 申请加急审核
- Google推出iOS功能性UI测试框架EarlGrey
- 绑定型service
- linux-test测试
- LeetCode_OJ【63】Unique Paths II
- 设计模式(6)---状态模式
- js中bind、call、apply函数的用法