Messenger可以在不同进程中传递Message对象,是一种轻量级的IPC方案,它的底层实现是AIDL。它对AIDL做了封装,使得我们可以更简单地进行进程间通信。它一次处理一个请求,因此在服务端我们不用考虑线程同步的问题。
//服务端
public class MessengerService extends Service{private static final String TAG="MessengerService";//接收消息 并且处理消息private static class MessengerHandler extends Handler{public void handleMessage(Message msg){switch(msg.what){case MyConstants.MSG_FROM_CLIENT::Log.i(TAG,"receive msg from Client:"+msg.getData().getString("msg"));//接收客户端发送的消息之后进行响应Messenger client=msg.replyTo;Messenge replyMessenge =Message.obtain(null,MyConstants,MSG_FROM_SERVICE);Bundle bundle=new Bundle();bundle.putString("reply","恩,你的消息我已经收到,稍后会回复你!");replyMessage.setData(bundle);try{client.send(replyMessage);}catch(Exception e){e.printStackTrace();}break;default:super.handleMessage(msg);}}}//将Messenger与Handler进行关联private final Messenger mMessenger =new Messenger(new MessengerHandler());//返回Messenger对象底层的Binder对象public IBinder onBind(Intent intent){return mMessenger.getBinder();}
}
//客户端
public class MessengerActivity extends Activity{private static final String TAG="MessengerActivity";private Messenger mService;//接收服务端 onBind()方法返回的IBinder对象private ServiceConnection mConnection =new ServiceConnection(){public void onServiceConnected(ComponentName className,IBinder service){//创建一个可以向服务器发送消息的Messenger对象mService =new Messenger(service);//构建消息对象Messenger msg=Message.obtain(null,MyConstants.MSG_FROM_CLIENT);Bundle data=new Bundle(); //利用Bundle来进行数据的传输data.putString("msg","hello,this is client.");msg.setData(data);///接收服务端回复的Messenger通过Message的replyTo参数传递给服务端msg.replyTo = mGetReplyMessenger;try{mService.send(msg);}catch(Exception e){e.printStackTrace();}}public void onServiceDisconnected(ComponentName className){}};//接收服务端的回复private Messenger mGetReplyMessenger =new Messenger(new MessengerHandler());private static class MessengerHandler extends Handler{public void handleMessage(Message msg){switch(msg.what){case MyConstants.MSG_FROM_SERVICE:Log.i(TAG,"receive msg from Service:"+msg.getData().getString("reply"));break;default:super.handleMessage(msg);}}}protected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_messenger);Intent intent =new Intent(this,MessengerService.class);bindService(intent,mConnection,Context.BIND_AUTO_CREATE);}protected void onDestroy(){unbindService(mConnection);super.onDestroy();}
}