Messager

2018-03-11  本文已影响0人  TakeItEasyJQ

不是用于并发,并且无法调用远程方法

Service

public class MessagerService extends Service{
    private static class MessageHandler extends Handler{
        public void handleMessage(Message msg){
            switch(msg.what){
                //获取到从Client发来的消息
                /*
                    调用msg . replyTo;获取到Messager对象来和Client联系起来
                    之后的操作为向Client发送回应
                    Client可以通过相同的方式获取到Service发送出去的消息
                */
                case MyContants.MSG_FROM_CLIENT :
                    Messager client=msg.replyTo;
                    Message replyMessage=Message . obtain(null , MyContants.MSG_FROM_SERVICE);
                    Bundle bundle=new Bundle();
                    bundle.putString("reply" , "ok I got");
                    replyMessage.setData(bundle);
                    try{
                        client.send(replyMessage);
                    }
                    break ;
                default :
                    break;
            }
        }
    }
    private final Messager mMessager =new Messager ( new MessagerHandler);
    //通过Handler对象创建Messager对象
    public IBinder onBind(Intent intent){
        return mMessagerr . getBinder();
        //返回IBinder对象
    }
}

Manifest中注册服务

Client中

public class MainActivity extends .....{
    private Messager mService;
    private ServiceConnection mconnection = new ServiceConnection(){
        public void onServiceConnected( ComponentName classname , IBinder service){
            /*
                此为Client像Service发送消息具体实现过程,
                1、获取Messager对象(Binder对象)messager
                2、创建Message、Bundle对象msg、data并写入消息于data中,以"msg"作为key;然后调用msg.sendData(data);
                3、调用messager . send(msg)像服务器发送此条Message
            */
            mService = new Messager(service); //是不是很眼熟,Binder对象
            Message message = Message.obtain( null , MyContains.MSG_FROM_CLIENT);
            Bundle data=new Bundle();
            data . putString("msg" , "hello , this is client");
            message.sentData(data);
            try{
                mService . send(message);
            }catch(Exception e){

            }
        }
    }
    protected void onCreate(Bundle savedInstanceState){
    //onCreate()中绑定
        Intent intent=new Intent(this , MessagerService.class);
        bindService(intent , mconnection , Context.BIND_AUTO_CREATE);
    }
    protected void onDestroy(){
    //onDestroy()中解除绑定
        unbindService(mconnection);
        super.onDestroy();
    }
}

msg.replyTo = mGetReplyMessager;

上一篇 下一篇

猜你喜欢

热点阅读