Android Messenger使用及分析

Messenger是基于AIDL实现的轻量级IPC方案。

1.使用

1.1服务端

接受信息的服务端需要实现一个Handler用于处理到的信息

    private static class MessengerHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_FROM_CLIENT:
                    Log.e(TAG, msg.getData().getString("msg"));;
                default:
                    break;
            }
        }
    }

然后用Messenger将Handler进行封装

  private final Messenger messenger = new Messenger(new MessengerHandler());

再通过onbinder函数返回messenger成员变量IMessenger的Binder,IMessenger实际上就是AIDL文件生成的接口,而Messenger对AIDL进行了封装。

    public IBinder onBind(Intent intent) {
        return messenger.getBinder();
    }

1.2客户端

通过ServiceConnection类的onServiceConnected获取到Binder,从而获取到服务端的Messenger代理类,调用send函数发送Message。所以Messenger能发送的信息只有Message能携带的信息。

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            serverMessenger = new Messenger(service);
            Message message = Message.obtain(null, MessengerService.MSG_FROM_CLIENT);
            Bundle data = new Bundle();
            data.putString("msg", "I am from the client.");
            message.setData(data);
            try{
                serverMessenger.send(message);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

1.3服务端返回客户端信息

同样是基于Messenger,客户端同需要学要实现一个带Handler的Messenger用于处理服务端返回的信息,而将客户端的Messenger传递给服务端是通过 Message的replyTo字段实现的,public Messenger replyTo;

  • 客户端代码
public class MessengerClient extends AppCompatActivity {

    private static final String TAG = "MessengerClient";
    public static final int FROM_SERVER = 1;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case FROM_SERVER:
                    Log.e(TAG, msg.getData().getString("reply"));
                    break;
                default:
                    break;
            }
        }
    };

    private Messenger clientMessenger = new Messenger(handler);

    private Messenger serverMessenger;

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            serverMessenger = new Messenger(service);
            Message message = Message.obtain(null, MessengerService.MSG_FROM_CLIENT);
            Bundle data = new Bundle();
            data.putString("msg", "I am from the client.");
            message.setData(data);
            message.replyTo = clientMessenger;
            try{
                serverMessenger.send(message);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent = new Intent(this, MessengerService.class);
        bindService(intent, connection, BIND_AUTO_CREATE);
    }

    @Override
    protected void onDestroy() {
        unbindService(connection);
        super.onDestroy();
    }
}

  • 服务端代码
package com.example.zhouk.testproject.aidl;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

public class MessengerService extends Service {
    private static final String TAG = "MessengerService";
    public static final int MSG_FROM_CLIENT = 112;

    private static class MessengerHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_FROM_CLIENT:
                    Log.e(TAG, msg.getData().getString("msg"));
                    Messenger clientMessenger = msg.replyTo;
                    Message replyMessage = Message.obtain(null, MessengerClient.FROM_SERVER);
                    Bundle data = new Bundle();
                    data.putString("reply", "I am from the server");
                    replyMessage.setData(data);
                    try {
                        clientMessenger.send(replyMessage);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    break;
            }
        }
    }

    private final Messenger messenger = new Messenger(new MessengerHandler());

    @Override
    public IBinder onBind(Intent intent) {
        return messenger.getBinder();
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章