public class MessengerService extends Service { /** Command to the service to display a message */ static final int MSG_SAY_HELLO = 1; /** * Handler of incoming messages from clients. */ class IncomingHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_SAY_HELLO: Toast.makeText(getApplicationContext(), "hello!", Toast.LENGTH_SHORT).show(); System.out.println(msg.getData().getString("info")); //实现双向通讯 Messenger client = msg.replyTo; Message replyMessage = Message.obtain(null, MSG_SAY_HELLO); for(int i = 0;i<20;i++){ try { Thread.sleep(500); Bundle bundle = new Bundle(); bundle.putString("reply", "嗯嗯,我已经收到你的第"+i+"条信息,稍后回复你。"); replyMessage.setData(bundle); try { client.send(replyMessage); } catch (RemoteException e) { e.printStackTrace(); } } catch (InterruptedException e) { e.printStackTrace(); } } break; default: super.handleMessage(msg); } } } /** * Target we publish for clients to send messages to IncomingHandler. */ final Messenger mMessenger = new Messenger(new IncomingHandler()); /** * When binding to the service, we return an interface to our messenger * for sending messages to the service. */ @Override public IBinder onBind(Intent intent) { Toast.makeText(getApplicationContext(), "binding", Toast.LENGTH_SHORT).show(); return mMessenger.getBinder(); } }
public void onServiceConnected(ComponentName className, IBinder service) { // This is called when the connection with the service has been // established, giving us the object we can use to // interact with the service. We are communicating with the // service using a Messenger, so here we get a client-side // representation of that from the raw IBinder object. mService = new Messenger(service); mBound = true; }
(2)声明一个Handler用来处理服务端的数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
private class MessengerHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case MessengerService.MSG_SAY_HELLO: System.out.println("receive from Service:" + msg.getData().get("reply")); TextView textView = new TextView(getApplicationContext()); textView.setTextColor(Color.BLACK); textView.setText("receive from Service:" + msg.getData().get("reply")); linearLayout.addView(textView); break; default: super.handleMessage(msg); } } }
(3)声明一个Messenger对象
1
private Messenger mGetReplyMessenger = new Messenger(new MessengerHandler());
(4)创建一个Message对象并用Messenger发送给服务
1 2 3 4 5 6 7 8 9 10 11 12 13 14
public void sayHello(View v) { if (!mBound) return; // Create and send a message to the service, using a supported 'what' value Message msg = Message.obtain(null, MessengerService.MSG_SAY_HELLO, 0, 0); Bundle bundle = new Bundle(); bundle.putString("info","呵呵哒"); msg.setData(bundle); msg.replyTo = mGetReplyMessenger; try { mService.send(msg); } catch (RemoteException e) { e.printStackTrace(); } }