服务端
package com.jay.msgapp2; import android.app.Service; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.os.Message; import android.os.Messenger; import android.os.RemoteException; import android.util.Log; public class BService extends Service { //记录下客户端发过来的 Messenger Messenger clientMessenger; //接受客户端发过来的消息 Messenger messenger = new Messenger(new Handler(Looper.myLooper()) { @Override public void handleMessage(Message msg) { //客户端发送来的数据 msg 中还有齐他参数,客户端发送过来都可以拿到 String clientData = msg.getData().getString("data"); //客户端的 Messenger 对象 clientMessenger = msg.replyTo; //发送数据返回给客户端 sendMsgToClient(); super.handleMessage(msg); } }); //服务端绑定器 @Override public IBinder onBind(Intent intent) { //绑定成功 return messenger.getBinder(); } //发送数据返回给客户端 private void sendMsgToClient(){ Message message = Message.obtain(); Bundle bundle = new Bundle(); bundle.putString("data","成功返回给客户端数据..."); message.setData(bundle); try { clientMessenger.send(message); } catch (RemoteException e) { e.printStackTrace(); } } }
客户端