Binder实现机制--应用分析
2016-05-23 08:49
323 查看
一.Binder裸实现--不用aidl,自己手动实现发送和接收: 核心在发送:transact调用,接收:onTransact <--Proxy封装transact,Stub封装onTransact,Stub实现要的操作接口 1.客户端 // myActivity.java // ……… public class myActivity extends Activity implements OnClickListener { private IBinder ib = null; public void onCreate(Bundle icicle) { super.onCreate(icicle); ... //------------------------------------------------------ bindService( new Intent("com.misoo.pk01.REMOTE_SERVICE"), mConnection, Context.BIND_AUTO_CREATE); } } private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className,IBinder ibinder) { ib = ibinder; } }; // 核心代码:Binder的transact的调用 public void onClick(View v) { switch (v.getId()) { case 101: // Play Button Parcel data = Parcel.obtain(); Parcel reply = Parcel.obtain(); try { ib.transact(1 , data, reply, 0); // 核心代码:发送数据 } catch (Exception e){ e.printStackTrace(); } break; case 102: // Stop Button data = Parcel.obtain(); reply = Parcel.obtain(); try { ib.transact(2, data, reply, 0); } catch (Exception e) { e.printStackTrace(); } break; case 103: finish(); break; } } 2.服务器端: public class myService extends Service { private IBinder mBinder = new myBinder(); @Override public IBinder onBind(Intent intent) { return mBinder; ] public class myBinder extends Binder{ // 核心代码:Binder的onTransact的调用 @Override public boolean onTransact( int code, Parcel data, // 核心代码:接收数据 Parcel reply, int flags) throws android.os.RemoteException { switch( code ){ case 1: // 调用第一个接口函数... break; case 2: // 调用第二个接口函数 break; } return true; } } 二.总结 1.客户端代码就是对<Play> 和<Stop> 两个功能进行”编码” 的动作。 case 101: // Play Button //….. ib.transact(1 , data, reply, 0); case 102: // Stop Button // ….. ib.transact(2, data, reply, 0); 2.服务器端代码就是对code进行“译码”动作。 如果code值為1就執行<Play> 動作; 如果code值為2就執行<Stop> 動作。
相关文章推荐
- 第12周项目1阅读程序写出运行结果3
- [2]R语言在数据处理上的禀赋之——可视化技术
- IMessenger源码
- session监听器(可用于统计在线人数,当前客户)
- 几个常见的停止错误
- 48. Rotate Image
- 作业 12周 Android应用性能优化
- 第十二周项目3—数组类运算的实现
- iOS开发系列--音频播放、录音、视频播放、拍照、视频录制
- iOS开发-继承特征详解
- iOS开发-继承特征详解
- selvlet开发入门
- SAP手工传输TP使用方法
- 第12周项目1阅读程序写出运行结果2
- 第十三周项目四 动物这样叫(1)
- cctv和世界上不存在网站FB
- druid简单教程
- nginx 静态服务器搭建
- java表达式问题 找零问题
- 针对苹果最新审核要求 为应用兼容IPv6