一、整体工程图

二、messenger_service_binding.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2.  
  3. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:padding="4dip"
  4. android:gravity="center_horizontal"
  5. android:layout_width="match_parent" android:layout_height="match_parent">
  6.  
  7. <TextView
  8. android:layout_width="match_parent" android:layout_height="wrap_content"
  9. android:layout_weight="0"
  10. android:paddingBottom="4dip"
  11. android:text="@string/messenger_service_binding"/>
  12.  
  13. <Button android:id="@+id/bind"
  14. android:layout_width="wrap_content" android:layout_height="wrap_content"
  15. android:text="@string/bind_service">
  16. <requestFocus />
  17. </Button>
  18.  
  19. <Button android:id="@+id/unbind"
  20. android:layout_width="wrap_content" android:layout_height="wrap_content"
  21. android:text="@string/unbind_service">
  22. </Button>
  23.  
  24. <TextView android:id="@+id/callback"
  25. android:layout_width="match_parent" android:layout_height="wrap_content"
  26. android:layout_weight="0"
  27. android:gravity="center_horizontal" android:paddingTop="4dip"/>
  28.  
  29. </LinearLayout>

三、AndroidManifest.xml

  1. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  2. package="com.jltxgcy.messengerservice"
  3. android:versionCode="1"
  4. android:versionName="1.0" >
  5.  
  6. <uses-sdk
  7. android:minSdkVersion="8"
  8. android:targetSdkVersion="15" />
  9.  
  10. <application
  11. android:icon="@drawable/ic_launcher"
  12. android:label="@string/app_name"
  13. android:theme="@style/AppTheme" >
  14. <activity
  15. android:name=".MessengerServiceActivities"
  16. android:label="@string/title_activity_messenger_service" >
  17. <intent-filter>
  18. <action android:name="android.intent.action.MAIN" />
  19.  
  20. <category android:name="android.intent.category.LAUNCHER" />
  21. </intent-filter>
  22. </activity>
  23. <service
  24. android:name=".MessengerService">
  25. </service>
  26. </application>
  27.  
  28. </manifest>

四、MessengerServiceActivities.java

  1. package com.jltxgcy.messengerservice;
  2.  
  3. import android.app.Activity;
  4. import android.content.ComponentName;
  5. import android.content.Context;
  6. import android.content.Intent;
  7. import android.content.ServiceConnection;
  8. import android.os.Bundle;
  9. import android.os.Handler;
  10. import android.os.IBinder;
  11. import android.os.Message;
  12. import android.os.Messenger;
  13. import android.os.RemoteException;
  14. import android.util.Log;
  15. import android.view.View;
  16. import android.view.View.OnClickListener;
  17. import android.widget.Button;
  18. import android.widget.TextView;
  19. import android.widget.Toast;
  20.  
  21. public class MessengerServiceActivities extends Activity{
  22.  
  23. Messenger mServiceMessage = null;
  24. boolean mIsBound;
  25. TextView mCallbackText;
  26.  
  27. class IncomingHandler extends Handler {
  28. @Override
  29. public void handleMessage(Message msg) {
  30. switch (msg.what) {
  31. case MessengerService.MSG_SET_VALUE:
  32. mCallbackText.setText("Received from service: " + msg.arg1);
  33. break;
  34. default:
  35. super.handleMessage(msg);
  36. }
  37. }
  38. }
  39.  
  40. final Messenger mMessenger = new Messenger(new IncomingHandler());
  41.  
  42. private ServiceConnection mConnection = new ServiceConnection() {
  43. public void onServiceConnected(ComponentName className,
  44. IBinder service) {
  45. mServiceMessage = new Messenger(service);
  46. mCallbackText.setText("Attached.");
  47. try {
  48. Message msg = Message.obtain(null,
  49. MessengerService.MSG_REGISTER_CLIENT);
  50. msg.replyTo = mMessenger;
  51.  
  52. mServiceMessage.send(msg);
  53. msg = Message.obtain(null,
  54. MessengerService.MSG_SET_VALUE, this.hashCode(), 0);
  55. mServiceMessage.send(msg);
  56. } catch (RemoteException e) {
  57. }
  58.  
  59. }
  60.  
  61. public void onServiceDisconnected(ComponentName className) {
  62. mServiceMessage = null;
  63. Log.d("jltxgcy", "onServiceDisconnected");
  64. }
  65. };
  66.  
  67. void doBindService() {
  68.  
  69. bindService(new Intent(MessengerServiceActivities.this,
  70. MessengerService.class), mConnection, Context.BIND_AUTO_CREATE);
  71. mIsBound = true;
  72. }
  73.  
  74. void doUnbindService() {
  75. if (mIsBound) {
  76. if (mServiceMessage != null) {
  77. try {
  78. Message msg = Message.obtain(null,
  79. MessengerService.MSG_UNREGISTER_CLIENT);
  80. msg.replyTo = mMessenger;
  81. mServiceMessage.send(msg);
  82. } catch (RemoteException e) {
  83. }
  84. }
  85.  
  86. unbindService(mConnection);
  87. mIsBound = false;
  88. }
  89. }
  90.  
  91. @Override
  92. protected void onCreate(Bundle savedInstanceState) {
  93. super.onCreate(savedInstanceState);
  94.  
  95. setContentView(R.layout.messenger_service_binding);
  96.  
  97. Button button = (Button)findViewById(R.id.bind);
  98. button.setOnClickListener(mBindListener);
  99. button = (Button)findViewById(R.id.unbind);
  100. button.setOnClickListener(mUnbindListener);
  101.  
  102. mCallbackText = (TextView)findViewById(R.id.callback);
  103.  
  104. }
  105.  
  106. private OnClickListener mBindListener = new OnClickListener() {
  107. public void onClick(View v) {
  108. doBindService();
  109. }
  110. };
  111.  
  112. private OnClickListener mUnbindListener = new OnClickListener() {
  113. public void onClick(View v) {
  114. doUnbindService();
  115. }
  116. };
  117.  
  118. }

五、MessengerService.java

  1. /*
  2. * Copyright (C) 2010 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16.  
  17. package com.jltxgcy.messengerservice;
  18.  
  19. import java.util.ArrayList;
  20.  
  21. import android.app.NotificationManager;
  22. import android.app.Service;
  23. import android.content.Intent;
  24. import android.os.Handler;
  25. import android.os.IBinder;
  26. import android.os.Message;
  27. import android.os.Messenger;
  28. import android.os.RemoteException;
  29. import android.util.Log;
  30. import android.widget.Toast;
  31.  
  32. public class MessengerService extends Service {
  33. private ArrayList<Messenger> mClients = new ArrayList<Messenger>();
  34. private int mValue = 0;
  35.  
  36. public static final String TAG = "jltxgcy";
  37.  
  38. public static final int MSG_REGISTER_CLIENT = 1;
  39.  
  40. public static final int MSG_UNREGISTER_CLIENT = 2;
  41.  
  42. public static final int MSG_SET_VALUE = 3;
  43.  
  44. class IncomingHandler extends Handler {
  45. @Override
  46. public void handleMessage(Message msg) {
  47. switch (msg.what) {
  48. case MSG_REGISTER_CLIENT:
  49. mClients.add(msg.replyTo);
  50. break;
  51. case MSG_UNREGISTER_CLIENT:
  52. mClients.remove(msg.replyTo);
  53. break;
  54. case MSG_SET_VALUE:
  55. mValue = msg.arg1;
  56. for (int i=mClients.size()-1; i>=0; i--) {
  57. try {
  58. mClients.get(i).send(Message.obtain(null,
  59. MSG_SET_VALUE, mValue, 0));
  60. } catch (RemoteException e) {
  61. mClients.remove(i);
  62. }
  63. }
  64. break;
  65. default:
  66. super.handleMessage(msg);
  67. }
  68. }
  69. }
  70.  
  71. final Messenger mMessenger = new Messenger(new IncomingHandler());
  72.  
  73. @Override
  74. public void onCreate() {
  75. Log.d(TAG, "onCreate");
  76. }
  77.  
  78. @Override
  79. public void onDestroy() {
  80. Log.d(TAG, "onDestroy");
  81. }
  82.  
  83. @Override
  84. public IBinder onBind(Intent intent) {
  85. Log.d(TAG, "onBind");
  86. return mMessenger.getBinder();
  87. }
  88.  
  89. @Override
  90. public boolean onUnbind(Intent intent) {
  91. Log.d(TAG, "onUnbind");
  92. return super.onUnbind(intent);
  93. }
  94.  
  95. }

六、详解

点击Bind Service,Logcat显示如下:

Service中:final Messenger mMessenger = new Messenger(new IncomingHandler());      onBind方法中mMessenger.getBinder()

Activity中, final Messenger mMessenger = new Messenger(new IncomingHandler());     onServiceConnected中mServiceMessage = new Messenger(service);

onBind方法中返回一个IBinder对象,onServiceConnected中,通过IBinder对象获取到了Messager对象。再通过msg.replyTo建立通信。

点击Unbind Service,Logcat显示如下:

运行结果如下:

获取message的方法:

  1. 1Message msg =new Message();
  2. msg.arg1=x;
  3. msg.arg2=x;
  4. msg.obj=x;
  5. msg.replyTo=x;
  6. msg.what=x;
  7. msg.setData(Bundle bundle);
  8. 2Message msg =Messge.obtain(Handler h, int what, int arg1, int arg2, Object obj);
  9. msg.replyTo=x;
  10. msg.setData(Bundle bundle);

MessagerService总结的更多相关文章

  1. Android面试,与Service交互方式

    五种交互方式,分别是:通过广播交互.通过共享文件交互.通过Messenger(信使)交互.通过自定义接口交互.通过AIDL交互.(可能更多) Service与Thread的区别 Thread:Thre ...

  2. SpringBoot | 第三十八章:基于RabbitMQ实现消息延迟队列方案

    前言 前段时间在编写通用的消息通知服务时,由于需要实现类似通知失败时,需要延后几分钟再次进行发送,进行多次尝试后,进入定时发送机制.此机制,在原先对接银联支付时,银联的异步通知也是类似的,在第一次通知 ...

  3. android 应用程序与服务端交互

    http://www.cnblogs.com/freeliver54/archive/2012/06/13/2547765.html 简述了Service的一些基础知识以及Service和Thread ...

随机推荐

  1. 【转】如何删除一个repository(仓库)

    原文网址:http://my.oschina.net/anna153/blog/377758?p=1 如何删除自己创建的一个项目,我浏览了一下github网站,确实不太容易找到删除功能.这里介绍一下啊 ...

  2. 流风ASP.NET框架商业版-工作流1.0简介

    流风ASP.NET框架商业版-工作流1.0简介 工作流简介 在流风ASP.NET框架商业版1.0推出后,就有集成工作流的想法,但是由于工作繁忙和其他事情的耽搁,时隔半年之久工作流1.0的版本才姗姗来迟 ...

  3. java内存模型和线程

    概述 多任务的处理在现在的计算机中可以说是"标配"了,在许多的情况下,让计算机同时做几件事情,不仅是因为计算机的运算能力的强大,还有一个重要的原因是:cpu的运算速度和计算机的存储 ...

  4. Day56

    今天干啦啥呢 早上七点起来 天气冷了真起不来啊 再坚持坚持就好了 今天上午九点开始考数据库 我去 大学四年第一次感觉到这样的爽  作弊的爽啊 也没有完全的作弊啦 是开卷考试,反正做的很顺利了. 我和胡 ...

  5. Spring 源码解读 推荐流程

    Spring源代码解析(一):IOC容器:http://www.javaeye.com/topic/86339 Spring源代码解析(二):IoC容器在Web容器中的启动:http://www.ja ...

  6. Wikioi 1080一维树状数组

    半个月时间最终把那些杂七杂八的学完了,尽管学完也,也仅仅是有了个模板,自己手敲还是不太行.所以如今開始要疯狂刷题了! ! .!!! 这题裸的树状数组.曾经写那道<敌兵布阵>的时候写过,所以 ...

  7. [Redux] React Todo List Example (Filtering Todos)

    /** * A reducer for a single todo * @param state * @param action * @returns {*} */ const todo = ( st ...

  8. Qt 界面使用自己定义控件 &quot;提升为&quot;

    1.效果图 我做了一个很easy的样例,一个能够显示颜色的QLabel,边上有个button,点击,跳出颜色选取的Dialog,然后选择一个颜色.这个QLabel会变成什么颜色. 2.ColorLab ...

  9. asp.net服务器向客户端弹出对话框,但不使页面边白板

    1: using System; 2: using System.Collections.Generic; 3: using System.Linq; 4: using System.Web; 5: ...

  10. 老生常谈的Javascript作用域问题

    在前端学习中,作用域这个问题一直被广泛提起,什么是作用域,什么又是作用域链?在Javascript中,怎么去理解这些概念都是学好这门语言的关键,所以在学习前端开发的过程中,我需要也很有必要去学习和总结 ...