您的位置:首页 > 其它

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> 動作。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: