Android进程间通信--Messenger

4.3 使用 Messenger 实现进程间通信

Messenger 是一种轻量级的IPC通信机制.底层使用的是AIDL机制.
Messenger 一次只处理一个请求因此不存在线程同步的问题.
Messenger传递的数据类型是 : Message 对象.

构造方法:

public Messenger(IBinder target) {
    mTarget = IMessenger.Stub.asInterface(target);
}
public Messenger(Handler target) {
    mTarget = target.getIMessenger();
}

实现Messenger的步骤 :

1, 服务端进程

1, 创建一个Service来处理客户端的请求.
2, 创建一个handler 用它来创建messenger对象.
3, 在Service的onBinder方法中返回这个Messenger底层的Binder对象即可.

2, 客户端进程

1, 绑定服务端的Service,绑定成功后用服务端返回的IBinder对象创建一个Messenger对象.
   通过这个Messenger就可以向服务端发送消息了.发送消息的类型为message 对象.
   
2, 如果需要服务端回复客户端就需要创建一个Handler,利用这个Handler 创建一个Messenger对象.
   Messenger对象通过message 的 replyTo 参数传递给服务端.

3, 示例代码

服务端关键代码

/**
 * 服务端进程.
 * Created by WSJ on 2016/9/29.
 */
public class MessengerService extends Service {
    private static final String TAG = "MessengerService";
    private static class MessengerHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case MyConstants.MSG_FROM_CLIENT :
                    Log.i(TAG,"rec from client : " + msg.getData().getString("msg"));
                    // 回复客户端
                    Messenger messenger = msg.replyTo;
                    Message message = Message.obtain(null,MyConstants.MSG_FROM_SERVICE);
                    Bundle data = new Bundle();
                    data.putString("msg","我已收到");
                    message.setData(data);
                    try {
                        messenger.send(message);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        // 返回Messenger底层的Binder对象.
        return mMessenger.getBinder();
    }
    // 根据Handler创建Messenger
    private final Messenger mMessenger = new Messenger(new MessengerHandler());
}

客户端关键代码

public class MessengerActivity extends AppCompatActivity {

    private static final String TAG = "MessengerActivity";
    /**
     * 向服务端发送数据的Messenger
     */
    private Messenger mService ;
    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // 根据获得Binder创建Messenger对象
            mService = new Messenger(service);
            Message msg = Message.obtain(null,MyConstants.MSG_FROM_CLIENT);
            Bundle data = new Bundle();
            data.putString("msg","hello this is client !");
            msg.setData(data);
            // 将Messenger设置
            msg.replyTo = mReplyMessenger;
            try {
                mService.send(msg);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

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

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

    private Messenger mReplyMessenger = new Messenger(new MessengerReplyHandler());
    /**
     * 接收服务端响应的Handler
     */
    private static class MessengerReplyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case MyConstants.MSG_FROM_SERVICE :
                    Log.i(TAG,"reply from server : " + msg.getData().get("msg"));
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }
}

备注 : Android开发艺术探索

你可能感兴趣的:(Android进程间通信--Messenger)