🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] 官方文档:[https://developer.android.com/guide/components/bound-services?hl=zh-cn](https://developer.android.com/guide/components/bound-services?hl=zh-cn) # 使用 Messenger的使用示例如下: Server端: ```java // MessengerService.java public class MessengerService extends Service { private static final String TAG = "MessengerService"; private static class MessengerHandler extends Handler { @Override public void handleMessage(@NonNull Message msg) { switch (msg.what) { case MyConstants.MSG_FROM_CLIENT: Log.i(TAG, "handleMessage: " + msg.getData().getString("msg")); Messenger client = msg.replyTo; Message replyMessage = Message.obtain(null, MyConstants.MSF_FROM_SERVICE); Bundle bundle = new Bundle(); bundle.putString("reply", "I has receive your msg"); replyMessage.setData(bundle); try { client.send(replyMessage); } catch (RemoteException e) { e.printStackTrace(); } break; default: super.handleMessage(msg); } } } private final Messenger mMessenger = new Messenger(new MessengerHandler()); @Nullable @Override public IBinder onBind(Intent intent) { return mMessenger.getBinder(); } } ``` Client端: ```java // MessengerActivity.java public class MessengerActivity extends AppCompatActivity { private static final String TAG = "MessengerActivity"; private Messenger mService; private ServiceConnection mServiceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { mService = new Messenger(service); Message message = Message.obtain(null, MyConstants.MSG_FROM_CLIENT); Bundle data = new Bundle(); data.putString("msg", "hello, this is client"); message.setData(data); message.replyTo = mGetReplyMessenger; try { mService.send(message); } catch (RemoteException e) { e.printStackTrace(); } } @Override public void onServiceDisconnected(ComponentName name) { } }; private Messenger mGetReplyMessenger = new Messenger(new MessengerHandler()); private static class MessengerHandler extends Handler { @Override public void handleMessage(@NonNull Message msg) { switch (msg.what) { case MyConstants.MSF_FROM_SERVICE: Log.i(TAG, "handleMessage: " + msg.getData().getString("reply")); break; default: break; } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_messenger); Intent intent = new Intent(this, MessengerService.class); bindService(intent, mServiceConnection, BIND_AUTO_CREATE); } @Override protected void onDestroy() { super.onDestroy(); unbindService(mServiceConnection); } } ``` # 源码分析 在Service中,根据Handler创建一个Messenger对象;然后的onBind方法中,返回的Binder对象是Messenger对象的getBinder()方法。首先从Messenger类看起: ```java // Messenger.java public final class Messenger implements Parcelable { private final IMessenger mTarget; public Messenger(Handler target) { mTarget = target.getIMessenger(); } public Messenger(IBinder target) { mTarget = IMessenger.Stub.asInterface(target); } public void send(Message message) throws RemoteException { mTarget.send(message); } public IBinder getBinder() { return mTarget.asBinder(); } // Parcelable序列化实现 //... } ``` Messenger只有一个成员变量,是IMessenger类型的mTarget。构造方法有如下两种重载: ```java // Messenger.java // 构造方法1 public Messenger(Handler target) { mTarget = target.getIMessenger(); } // 构造方法2 public Messenger(IBinder target) { mTarget = IMessenger.Stub.asInterface(target); } ``` 其中,方法1适用于在Service中根据Handler构造Messenger;方法2适用于在Client中从IBinder对象生成Messenger。 ## Service中实现 ```java // MessengerService.java private final Messenger mMessenger = new Messenger(new MessengerHandler()); @Nullable @Override public IBinder onBind(Intent intent) { return mMessenger.getBinder(); } ``` 其中Messenger构造方法如下: ```java // Messenger.java public Messenger(Handler target) { mTarget = target.getIMessenger(); } ``` 调用Handler对象的getIMessenger方法来为成员变量mTarget进行赋值: ```java // Handler.java IMessenger mMessenger; final IMessenger getIMessenger() { synchronized (mQueue) { if (mMessenger != null) { return mMessenger; } mMessenger = new MessengerImpl(); return mMessenger; } } ``` ```java // Handler.java#MessengerImpl private final class MessengerImpl extends IMessenger.Stub { public void send(Message msg) { msg.sendingUid = Binder.getCallingUid(); Handler.this.sendMessage(msg); } } ``` 其中MessengerImpl是IMessenger.Stub的实现类。 * Handler中IMessenger类型的成员变量mMessenger,就是Messenger中的IMessenger类型的成员变量mTarget,也是整个跨进程调用中最重要的对象。 * 在Service的onBind方法中调用Messenger对象的getBinder方法获得mTarget跨进程传递。 * 在Client中,拿到IBinder对象后,根据IBinder创建出Messenger对象,当调用Messenger对象的send方法时,其实调用的就是Service中Handler的sendMessage方法。 ***** 方法2中,参数是IBinder对象时,调用IMessenger.Stub的asInterface方法获得远程对象。IMessenger的AIDL文件声明如下: ```plain // IMessenger.aidl package android.os; import android.os.Message; oneway interface IMessenger { void send(in Message msg); } ``` ## Client中实现 在Client中拿到IBinder对象后,调用Messenger的构造方法2获得Messenger对象: ```java // Messenger.java public Messenger(IBinder target) { mTarget = IMessenger.Stub.asInterface(target); } ``` 调用Messenger的send方法发送消息: ```java // MessengerActivity.java(Client类) mService.send(message); ``` ```java public void send(Message message) throws RemoteException { mTarget.send(message); } ``` mTarget即IMessenger的实现为: ```java // Handler.java#MessengerImpl private final class MessengerImpl extends IMessenger.Stub { public void send(Message msg) { msg.sendingUid = Binder.getCallingUid(); Handler.this.sendMessage(msg); } } ``` 可以看到,调用了Service中的Handler的sendMessage方法。 ## 总结 可以看到,Messenger对AIDL进行了封装,我们在整个使用中对于AIDL是无感的,只需要使用Messenger这个信使来进行消息的传递即可。关键思路如下: 1、Messenger类拥有一个重要的成员变量mTarget,是IMessenger类型的 2、Handler中拥有IMessenger类的默认实现,在Service中创建一个Handler,然后从Handler中获取IMessenger实现,赋值给新创建的Messenger 4、Service的onBind方法中返回的IBinder对象,其实就是Messenger的成员变量mTarget 5、Client的onServiceConnected方法中,拿到IBinder对象后,根据IBinder对象创建一个Messenger对象,IBinder对象的主要作用是初始化了Messenger类的mTarget成员变量 6、Client需要跨进程调用时,调用Client中Messenger对象的send方法,实际上是调用了mTarget的send方法,默认实现在Service的Handler中,也就是调用Handler发送消息。