Messenger可以译为信使,顾名思义,可以通过它在不同进程中传递Message对象,在Message中放入我们需要传递的数据,就可以轻松地实现数据的进程间传递了。Messenger是一种轻量级的IPC方案,底层实现是AIDL,使用起来也很简单。首先需要在服务端进程中创建一个Service来处理客户端的连接请求,同时创建出一个Handler并通过它来创建一个Messenger对象,然后在Service的onBind中返回这个Messenger对象底层的Binder即可;接着在客户端进程中绑定服务端的Service,绑定成功后用服务端的IBinder对象创建出一个Messenger,通过这个Messenger就可以向服务端发送消息了,发消息类型为Message对象。如果需要服务端能够回复客户端,就和服务端一样,还需要创建一个Handler并创建一个Messenger,并把这个Messenger对象通过Message的replyTo参数传递给服务端,服务端通过这个replyTo参数就可以回复客户端。下面通过简单的例子来讲解:
//服务端代码,需要在AndroidManifest里面注册服务
public class MessengerService extends Service {
private static final String TAG = "MessengerService";
//Handler处理客户端发过来的消息
private static class MessengerHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
Log.e(TAG,"receive msg fron client:"+msg.getData().getString("msg"));
//拿到客户端Messenger对象,回复消息
Messenger client = msg.replyTo;
Message replyMessage = Message.obtain(null,1);
Bundle bundle = new Bundle();
bundle.putString("reply","okay, i have got you request");
replyMessage.setData(bundle);
try {
client.send(replyMessage);
} catch (RemoteException e) {
e.printStackTrace();
}
break;
default:
super.handleMessage(msg);
}
}
}
//创建Messenger对象,构造函数如下
//public Messenger(Handler target) {
// mTarget = target.getIMessenger();
//}
private final Messenger messenger = new Messenger(new MessengerHandler());
//返回Messenger对象的底层Binder
@Nullable
@Override
public IBinder onBind(Intent intent) {
return messenger.getBinder();
}
}
// 客户端代码
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private Messenger mService;
//实例化ServiceConnection对象
private ServiceConnection con = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//创建Messenger对象,构造函数如下
//public Messenger(IBinder target) {
//mTarget = IMessenger.Stub.asInterface(target);
//}
mService = new Messenger(service);
Message msg = Message.obtain(null,0);
Bundle bundle = new Bundle();
bundle.putString("msg","hello,this is from client");
msg.setData(bundle);
msg.replyTo = replyMessenger;
try {
mService.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
//Messenger对象接收服务端消息
private Messenger replyMessenger = new Messenger(new MessengerHandler());
private static class MessengerHandler extends Handler {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 1) {
Log.e(TAG,"receive msg fron server:"+msg.getData().getString("reply"));
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this,MessengerService.class);
bindService(intent,con, Context.BIND_AUTO_CREATE);
}
@Override
protected void onDestroy() {
unbindService(con);
super.onDestroy();
}
}
如下为Messenger原理图:
Messenger.jpg
网友评论