不是用于并发,并且无法调用远程方法
- Service中
1、Service中创建一个Handler并用它来创建Messager对象
2、在onBind()方法中返回此Messager对象的底层binder - Client中
1、绑定Service后用service返回的IBindler对象创建Messager对象
2、若想Service可以回应Client,则重复Service中的动作
Service
public class MessagerService extends Service{
private static class MessageHandler extends Handler{
public void handleMessage(Message msg){
switch(msg.what){
//获取到从Client发来的消息
/*
调用msg . replyTo;获取到Messager对象来和Client联系起来
之后的操作为向Client发送回应
Client可以通过相同的方式获取到Service发送出去的消息
*/
case MyContants.MSG_FROM_CLIENT :
Messager client=msg.replyTo;
Message replyMessage=Message . obtain(null , MyContants.MSG_FROM_SERVICE);
Bundle bundle=new Bundle();
bundle.putString("reply" , "ok I got");
replyMessage.setData(bundle);
try{
client.send(replyMessage);
}
break ;
default :
break;
}
}
}
private final Messager mMessager =new Messager ( new MessagerHandler);
//通过Handler对象创建Messager对象
public IBinder onBind(Intent intent){
return mMessagerr . getBinder();
//返回IBinder对象
}
}
去Manifest中注册服务
Client中
public class MainActivity extends .....{
private Messager mService;
private ServiceConnection mconnection = new ServiceConnection(){
public void onServiceConnected( ComponentName classname , IBinder service){
/*
此为Client像Service发送消息具体实现过程,
1、获取Messager对象(Binder对象)messager
2、创建Message、Bundle对象msg、data并写入消息于data中,以"msg"作为key;然后调用msg.sendData(data);
3、调用messager . send(msg)像服务器发送此条Message
*/
mService = new Messager(service); //是不是很眼熟,Binder对象
Message message = Message.obtain( null , MyContains.MSG_FROM_CLIENT);
Bundle data=new Bundle();
data . putString("msg" , "hello , this is client");
message.sentData(data);
try{
mService . send(message);
}catch(Exception e){
}
}
}
protected void onCreate(Bundle savedInstanceState){
//onCreate()中绑定
Intent intent=new Intent(this , MessagerService.class);
bindService(intent , mconnection , Context.BIND_AUTO_CREATE);
}
protected void onDestroy(){
//onDestroy()中解除绑定
unbindService(mconnection);
super.onDestroy();
}
}
msg.replyTo = mGetReplyMessager;