如果你需要你的service和其他进程通信,那么你可以使用一个Messenger来提供这个接口。

这种方法允许你在不使用 AIDL的情况下,进行跨进程通信IPC。

实现步骤

下面是一个如何使用 Messenger的小总结:

  1. service实现一个 Handler 接收客户端每一次调用的回调。

  2. Handler 用来创建一个Messenger对象,它是一个Handler的引用。

  3. Messenger创建一个 IBinder,service从 onBind()中把它返回给客户端。

  4. 客户端使用这个IBinder来实例化Messenger (service的Handler的引用),客户端使用它来向service发送Message对象。

  5. service在它的Handler中接收每一个Message对象,在它的 handleMessage()方法中。

Code

  1. public class MessengerService extends Service
  2. {
  3. /** Command to the service to display a message */
  4. static final int MSG_SAY_HELLO = 1;
  5.  
  6. /**
  7. * Handler of incoming messages from clients.
  8. */
  9. class IncomingHandler extends Handler
  10. {
  11. @Override
  12. public void handleMessage(Message msg)
  13. {
  14. switch (msg.what)
  15. {
  16. case MSG_SAY_HELLO:
  17. Toast.makeText(getApplicationContext(), "hello!",
  18. Toast.LENGTH_SHORT).show();
  19. break;
  20. default:
  21. super.handleMessage(msg);
  22. }
  23. }
  24. }
  25.  
  26. /**
  27. * Target we publish for clients to send messages to IncomingHandler.
  28. */
  29. final Messenger mMessenger = new Messenger(new IncomingHandler());
  30.  
  31. /**
  32. * When binding to the service, we return an interface to our messenger for
  33. * sending messages to the service.
  34. */
  35. @Override
  36. public IBinder onBind(Intent intent)
  37. {
  38. Toast.makeText(getApplicationContext(), "binding", Toast.LENGTH_SHORT)
  39. .show();
  40. return mMessenger.getBinder();
  41. }
  42. }

  注意 Handler中的 handleMessage() 方法是service接收到来的 Message并且决定做什么的地方。

  客户端需要做的仅仅是创建一个基于service所返回的 IBinder的 Messenger,然后用 send()方法发送信息。

  比如,这里有一个简单的activity和service绑定并且发送信息给service:

  1. public class ActivityMessenger extends Activity
  2. {
  3. /** Messenger for communicating with the service. */
  4. Messenger mService = null;
  5.  
  6. /** Flag indicating whether we have called bind on the service. */
  7. boolean mBound;
  8.  
  9. /**
  10. * Class for interacting with the main interface of the service.
  11. */
  12. private ServiceConnection mConnection = new ServiceConnection()
  13. {
  14. public void onServiceConnected(ComponentName className, IBinder service)
  15. {
  16. // This is called when the connection with the service has been
  17. // established, giving us the object we can use to
  18. // interact with the service. We are communicating with the
  19. // service using a Messenger, so here we get a client-side
  20. // representation of that from the raw IBinder object.
  21. mService = new Messenger(service);
  22. mBound = true;
  23. }
  24.  
  25. public void onServiceDisconnected(ComponentName className)
  26. {
  27. // This is called when the connection with the service has been
  28. // unexpectedly disconnected -- that is, its process crashed.
  29. mService = null;
  30. mBound = false;
  31. }
  32. };
  33.  
  34. public void sayHello(View v)
  35. {
  36. if (!mBound)
  37. return;
  38. // Create and send a message to the service, using a supported 'what'
  39. // value
  40. Message msg = Message
  41. .obtain(null, MessengerService.MSG_SAY_HELLO, 0, 0);
  42. try
  43. {
  44. mService.send(msg);
  45. }
  46. catch (RemoteException e)
  47. {
  48. e.printStackTrace();
  49. }
  50. }
  51.  
  52. @Override
  53. protected void onCreate(Bundle savedInstanceState)
  54. {
  55. super.onCreate(savedInstanceState);
  56. setContentView(R.layout.main);
  57. }
  58.  
  59. @Override
  60. protected void onStart()
  61. {
  62. super.onStart();
  63. // Bind to the service
  64. bindService(new Intent(this, MessengerService.class), mConnection,
  65. Context.BIND_AUTO_CREATE);
  66. }
  67.  
  68. @Override
  69. protected void onStop()
  70. {
  71. super.onStop();
  72. // Unbind from the service
  73. if (mBound)
  74. {
  75. unbindService(mConnection);
  76. mBound = false;
  77. }
  78. }
  79. }

  注意这个例子并没有展示service如何响应客户端,如果你想要service响应,你需要在客户端中创建一个 Messenger。

  然后当客户端接收到onServiceConnected()回调方法时,它会发送一个 Message到service,在它的send() 方法的replyTo参数中包含了客户端的Messenger。

我是天王盖地虎的分割线

参考:http://www.cnblogs.com/mengdd/tag/Android/default.html?page=4

Android -- Messenger与Service的更多相关文章

  1. (转载)Android中的Service:Binder,Messenger,AIDL(2)

    前言 前面一篇博文介绍了关于Service的一些基本知识,包括service是什么,怎么创建一个service,创建了一个service之后如何启动它等等.在这一篇博文里有一些需要前一篇铺垫的东西,建 ...

  2. (转载)所有分类 > 开发语言与工具 > 移动开发 > Android开发 Android中的Service:默默的奉献者 (1)

    前言 这段时间在看一些IPC相关的东西,这里面就不可避免的要涉及到service,进程线程这些知识点,而且在研究的过程中我惊觉自己对这些东西的记忆已经开始有些模糊了——这可要不得.于是我就干脆花了点心 ...

  3. Android 面试题--Service

    1.Service 是否在 main thread 中执行, service 里面是否能执行耗时的操作?默认情况,如果没有显示的指 servic 所运行的进程, Service 和 activity ...

  4. Android探索之Service全面回顾及总结

    什么是Service? Service(服务)是Android提供的四大组件之一,是一个没有用户界面的在后台运行执行耗时操作的应用组件.其他应用组件能够启动Service,并且当用户切换到另外的应用场 ...

  5. Android 中的 Service 全面总结(转载)

    转载地址:http://www.cnblogs.com/newcj/archive/2011/05/30/2061370.html 感谢作者 Android 中的 Service 全面总结 1.Ser ...

  6. java攻城狮之路(Android篇)--BroadcastReceiver&Service

    四大组件:activity 显示. contentProvider 对外暴露自己的数据给其他的应用程序.BroadcastReceiver 广播接收者,必须指定要接收的广播类型.必须明确的指定acti ...

  7. 图解Android - Binder 和 Service

    在 Zygote启动过程 一文中我们说道,Zygote一生中最重要的一件事就是生下了 System Server 这个大儿子,System Server 担负着提供系统 Service的重任,在深入了 ...

  8. Android 服务类Service 的详细学习

    http://blog.csdn.net/vipzjyno1/article/details/26004831 Android服务类Service学习四大组建   目录(?)[+] 什么是服务 服务有 ...

  9. 大仙说道之Android studio实现Service AIDL

    今天要开发过程中要用到AIDL的调用,之前用的eclipse有大量教程,用起来很方便,现在刚换了Android studio,不可否认studio真的很强大,只是很多功能还需要摸索. AIDL(And ...

随机推荐

  1. AFF镜像工具集afflib-tools

    AFF镜像工具集afflib-tools   Advanced Forensic Format(AFF)是一种开源免费的磁盘镜像格式.作为磁盘数字取证的三大格式之一,AFF提供数字取证的各项功能,如签 ...

  2. XamarinForms教程构建XamarinForms开发环境

    构建XamarinForms开发环境 所谓Xamarin.Forms的开发环境,就是指在基本硬件和数字软件的基础上,为支持系统软件和应用软件的工程化开发和维护而使用的一组软件,简称SDE.对于任何的程 ...

  3. 光线求交-面、三角形、球 (Ray intersection)

    光线求交 光线定义:position \(a(t)\) = \(o\) + \(t\vec{d}\); 球定义: center p, radius r; 平面定义:normal \(\vec{n}\) ...

  4. Selenium模拟登陆简书

    from selenium import webdriver from selenium.webdriver import ActionChains from selenium.webdriver.c ...

  5. 【BZOJ 3560】 3560: DZY Loves Math V (欧拉函数)

    3560: DZY Loves Math V Time Limit: 10 Sec  Memory Limit: 256 MBSubmit: 241  Solved: 133 Description ...

  6. 【左偏树+贪心】BZOJ1367-[Baltic2004]sequence

    [题目大意] 给定一个序列t1,t2,...,tn ,求一个递增序列z1<z2<...<zn , 使得R=|t1−z1|+|t2−z2|+...+|tn−zn| 的值最小.本题中,我 ...

  7. [转]php-fpm - 启动参数及重要配置详解

    约定几个目录/usr/local/php/sbin/php-fpm/usr/local/php/etc/php-fpm.conf/usr/local/php/etc/php.ini 一,php-fpm ...

  8. MongoDB,pymongo

    MongoDB: 数据库,nosql [{ id:1 name:"蔡文姬" age: 16 gender:"女" }, { id:1 name:"蔡文 ...

  9. [HEOI2013]SAO

    题目大意: 一个有向无环图上有n个结点, 现在告诉你n-1个条件(x,y),表示x和y的先后关系. 问原图共有几种可能的拓扑序? 思路: 树形DP. f[i][j]表示对于第i个结点,有j个点在它前面 ...

  10. NOIP 解题有感

    算法方面: 在搜索问题上,包括贪心等没有固定算法的题目,还有输出格式(包括输入格式)特别容易出错.这也是解题选手的弱点. 1.做搜索题把步骤先用文字写下来,再转换成代码,以避免敲代码时疏漏某个条件. ...