通过AIDL进程间通信

AIDL只不过是一种简化代码书写的方法,进程间通信实际上是由binder机制实现,AIDL本身不具备进程间通信的功能。


通俗点来说,binder机制的使用:大家(客户端和服务端)都定义有相同的AIDL接口,你实现的那部分接口由我来调用,我实现的由你调用;

那如何实现方法的调用呢,本质来说就是将各自的对象传递过去(Service-->Client : onBind()返回的Binder转化为AIDL接口所属的实例;Client-->Service:client的实例作为参数传入由client调用的方法中)

//服务端
//AIDL文件
package com.leo.aidl;
interface infa {
methodInvokedByClient(Object o);
methodInvokedByService();
}
//服务端Service
public class sv extends Service {
	//用于获得客户端创建的实例,从而调用由客户端实现的方法
	Object o;
	//实现infa接口的Binder类
	private Binder mBinder = new infa.Stub()
	{
	//实现methodInvokedByClient
	public void methodInvokedByClient(Object o){..,this.o = o, ..};//<span style="font-family: Arial, Helvetica, sans-serif;">client的实例作为参数传入由client调用的方法中</span><div>
</div>
	}
	//onBind返回mBinder
	public IBinder onBind(Intent intent) 
	{ return mBinder;}
  	//调用由客户端实现的方法methodInvokedByService()
	o.methodInvokedByService();
}

//客户端
//AIDL文件
package com.leo.aidl;
interface infa {
methodInvokedByClient(Object o);
methodInvokedByService();
}
//客户端activity
public class a extends Activity {
Object o ;
protected void onCreate(...)
 {
	//请求连接服务端
	bindService(.. , mConnection ,...);
}

private ServiceConnection mConnection = new ServiceConnection()
{
	
//onBind被调用后,系统会回调onServiceConnection
	public void onServiceConnected(... , IBinder service)
	{
        //将Binder转化为infa的实现类对象
	infa i = infa.Stub.asInterface(service);
	//此时客户端就可以调用服务端的方法了,同时也将客户端定义的实例传输到了服务端
	i.methodInvokedByClient(o);
	}
}

//实现methodInvokedByService
public void methodInvokedByService() {...};
}




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值