Messenger:信使
官方文檔解釋:它引用了一個Handler對象,以便others能夠向它發送消息(使用mMessenger.send(Message msg)方法)。該類允許跨進程間基於Message的通信(即兩個進程間可以通過Message進行通信),在服務端使用Handler創建一個Messenger,客戶端持有這個Messenger就可以與服務端通信了。
以前我們使用Handler+Message的方式進行通信,都是在同一個進程中,從線程持有一個主線程的Handler對象,並向主線程發送消息。
而Android既然可以使用bindler機制進行跨進行通信,所以我們當然可以將Handler與bindler結合起來進行跨進程發送消息。
查看API就可以發現,Messenger就是這種方式的實現。
一般使用方法如下:
1。遠程通過
mMessenger = new Messenger(mHandler)
創建一個信使對象
2。客戶端使用bindlerService請求連接遠程
3。遠程onBind方法返回一個bindler
return mMessenger.getBinder();
4.客戶端使用遠程返回的bindler得到一個信使(即得到遠程信使)
public void onServiceConnected(ComponentName name, IBinder service) {
rMessenger = new Messenger(service);
......
}
這裡雖然是new了一個Messenger,但我們查看它的實現
public Messenger(IBinder target) { mTarget = IMessenger.Stub.asInterface(target); }
發現它的mTarget是通過Aidl得到的,實際上就是遠程創建的那個。
5。客戶端可以使用這個遠程信使對象向遠程發送消息:rMessenger.send(msg);
這樣遠程服務端的Handler對象就能收到消息了,然後可以在其handlerMessage(Message msg)方法中進行處理。(該Handler對象就是第一步服務端創建Messenger時使用的參數mHandler).
經過這5個步驟貌似只有客戶端向服務端發送消息,這樣的消息傳遞是單向的,那麼如何實現雙向傳遞呢?
首先需要在第5步稍加修改,在send(msg)前通過msm.replyTo = mMessenger將自己的信使設置到消息中,這樣服務端接收到消息時同時也得到了客戶端的信使對象了,然後服務端可以通過/得到客戶端的信使對象,並向它發送消息 cMessenger = msg.replyTo; cMessenger.send(message);
即完成了從服務端向客戶端發送消息的功能,這樣客服端可以在自己的Handler對象的handlerMessage方法中接收服務端發送來的message進行處理。
雙向通信宣告完成。
以下代碼來自ApiDemo
Service code:
[java]
- public class MessengerService extends Service {
- /** For showing and hiding our notification. */
- NotificationManager mNM;
- /** Keeps track of all current registered clients. */
- ArrayList<Messenger> mClients = new ArrayList<Messenger>();
- /** Holds last value set by a client. */
- int mValue = 0;
-
- /**
- * Command to the service to register a client, receiving callbacks
- * from the service. The Message's replyTo field must be a Messenger of
- * the client where callbacks should be sent.
- */
- static final int MSG_REGISTER_CLIENT = 1;
-
- /**
- * Command to the service to unregister a client, ot stop receiving callbacks
- * from the service. The Message's replyTo field must be a Messenger of
- * the client as previously given with MSG_REGISTER_CLIENT.
- */
- static final int MSG_UNREGISTER_CLIENT = 2;
-
- /**
- * Command to service to set a new value. This can be sent to the
- * service to supply a new value, and will be sent by the service to
- * any registered clients with the new value.
- */
- static final int MSG_SET_VALUE = 3;
-
- /**
- * Handler of incoming messages from clients.
- */
- class IncomingHandler extends Handler {
- @Override
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case MSG_REGISTER_CLIENT:
- mClients.add(msg.replyTo);
- break;
- case MSG_UNREGISTER_CLIENT:
- mClients.remove(msg.replyTo);
- break;
- case MSG_SET_VALUE:
- mValue = msg.arg1;
- for (int i = mClients.size() - 1; i >= 0; i --) {
- try {
- mClients.get(i).send(Message.obtain(null,
- MSG_SET_VALUE, mValue, 0));
- } catch (RemoteException e) {
- // The client is dead. Remove it from the list;
- // we are going through the list from back to front
- // so this is safe to do inside the loop.
- mClients.remove(i);
- }
- }
- break;
- default:
- super.handleMessage(msg);
- }
- }
- }
-
- /**
- * Target we publish for clients to send messages to IncomingHandler.
- */
- final Messenger mMessenger = new Messenger(new IncomingHandler());
-
- @Override
- public void onCreate() {
- mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
-
- // Display a notification about us starting.
- showNotification();
- }
-
- @Override
- public void onDestroy() {
- // Cancel the persistent notification.
- mNM.cancel(R.string.remote_service_started);
-
- // Tell the user we stopped.
- Toast.makeText(this, R.string.remote_service_stopped, Toast.LENGTH_SHORT).show();
- }
-
- /**
- * When binding to the service, we return an interface to our messenger
- * for sending messages to the service.
- */
- @Override
- public IBinder onBind(Intent intent) {
- return mMessenger.getBinder();
- }
-
- /**
- * Show a notification while this service is running.
- */
- private void showNotification() {
- // In this sample, we'll use the same text for the ticker and the expanded notification
- CharSequence text = getText(R.string.remote_service_started);
-
- // Set the icon, scrolling text and timestamp
- Notification notification = new Notification(R.drawable.stat_sample, text,
- System.currentTimeMillis());
-
- // The PendingIntent to launch our activity if the user selects this notification
- PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
- new Intent(this, Controller.class), 0);
-
- // Set the info for the views that show in the notification panel.
- notification.setLatestEventInfo(this, getText(R.string.remote_service_label),
- text, contentIntent);
-
- // Send the notification.
- // We use a string id because it is a unique number. We use it later to cancel.
- mNM.notify(R.string.remote_service_started, notification);
- }
- }