【起航计划 036】2015 起航计划 Android APIDemo的魔鬼步伐 35 App->Service->Messenger Service Messenger实现进程间通信
前面LocalService 主要是提供同一Application中组件来使用,如果希望支持不同应用或进程使用Service。可以通过Messenger。使用Messgener可以用来支持进程间通信而无需使用AIDL。
下面步骤说明里Messenger的使用方法:
- 在Service中定义一个Handler来处理来自Client的请求。
- 使用这个Handler创建一个Messenger (含有对Handler的引用).
- Messenger创建一个IBinder对象返回给Client( onBind方法)。
- Client 使用从Service返回的IBinder重新构造一个Messenger 对象,提供这个Messenger对象可以给Service 发送消息。
- Service提供Handler接受来自Client的消息Message. 提供handleMessage来处理消息。
在这种方式下,Service没有定义可以供Client直接调用的方法。而是通过”Message”来传递信息。
本例Messenger Service 涉及到两个类 MessengerServiceActivities 和 MessengerService.
首先看看Service的定义,在MessengerService定义了一个IncomingHandler ,用于处理来自Client的消息。
/**
* Handler of incoming messages from clients.
*/
class IncomingHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_REGISTER_CLIENT:
mClients.add(msg.replyTo);
break;
case MSG_UNREGISTER_CLIENT:
mClients.remove(msg.replyTo);
break;
case MSG_SET_VALUE:
mValue = msg.arg1;
for (int i=mClients.size()-1; i>=0; i--) {
try {
mClients.get(i).send(Message.obtain(null,
MSG_SET_VALUE, mValue, 0));
} catch (RemoteException e) {
// The client is dead. Remove it from the list;
// we are going through the list from back to front
// so this is safe to do inside the loop.
mClients.remove(i);
}
}
break;
default:
super.handleMessage(msg);
}
}
}
然后使用这个IncomingHandler定义一个Messenger:
/**
* Target we publish for clients to send messages to IncomingHandler.
*/
final Messenger mMessenger = new Messenger(new IncomingHandler());
应为这种方法采用的“Bound” Service模式,onBind 需要返回一个IBind对象, 可以通过mMessenger.getBinder()返回与这个Messenger关联的IBinder对象,Client可以通过这个IBinder 对象重新构造一个Messenger对象,从而建立起与Service之间的通信链路。
/**
* When binding to the service, we return an interface to our messenger
* for sending messages to the service.
*/
@Override
public IBinder onBind(Intent intent) {
return mMessenger.getBinder();
}
再看看Client 的代码MessengerServiceActivities 在 ServiceConnection的 onServiceConnected的定义,这个方法返回MessengerService 的onBind 定义的IBinder对象:
public void onServiceConnected(ComponentName className,
IBinder service) {
// This is called when the connection with the service has been
// established, giving us the service object we can use to
// interact with the service. We are communicating with our
// service through an IDL interface, so get a client-side
// representation of that from the raw service object.
mService = new Messenger(service);
mCallbackText.setText("Attached."); // We want to monitor the service for as long as we are
// connected to it.
try {
Message msg = Message.obtain(null,
MessengerService.MSG_REGISTER_CLIENT);
msg.replyTo = mMessenger;
mService.send(msg); // Give it some value as an example.
msg = Message.obtain(null,
MessengerService.MSG_SET_VALUE, this.hashCode(), 0);
mService.send(msg);
} catch (RemoteException e) {
// In this case the service has crashed before we could even
// do anything with it; we can count on soon being
// disconnected (and then reconnected if it can be restarted)
// so there is no need to do anything here.
} // As part of the sample, tell the user what happened.
Toast.makeText(Binding.this, R.string.remote_service_connected,
Toast.LENGTH_SHORT).show();
}
本例实现了Client与Service 之间的双向通信,因此在Client也定义了一个Messenger对象mMessenger,用于处理来自Service的消息。
有了 mService对象,就可以使用send向Service发送消息,如过需要Service 返回信息,可以定义message.replyTo 对象。

【起航计划 036】2015 起航计划 Android APIDemo的魔鬼步伐 35 App->Service->Messenger Service Messenger实现进程间通信的更多相关文章
- 【起航计划 002】2015 起航计划 Android APIDemo的魔鬼步伐 01
本文链接:[起航计划 002]2015 起航计划 Android APIDemo的魔鬼步伐 01 参考链接:http://blog.csdn.net/column/details/mapdigitap ...
- 【起航计划 037】2015 起航计划 Android APIDemo的魔鬼步伐 36 App->Service->Remote Service Binding AIDL实现不同进程间调用服务接口 kill 进程
本例和下个例子Remote Service Controller 涉及到的文件有RemoteService.java ,IRemoteService.aidl, IRemoteServiceCallb ...
- 【起航计划 031】2015 起航计划 Android APIDemo的魔鬼步伐 30 App->Preferences->Advanced preferences 自定义preference OnPreferenceChangeListener
前篇文章Android ApiDemo示例解析(31):App->Preferences->Launching preferences 中用到了Advanced preferences 中 ...
- 【起航计划 027】2015 起航计划 Android APIDemo的魔鬼步伐 26 App->Preferences->Preferences from XML 偏好设置界面
我们在前面的例子Android ApiDemo示例解析(9):App->Activity->Persistent State 介绍了可以使用Shared Preferences来存储一些状 ...
- 【起航计划 020】2015 起航计划 Android APIDemo的魔鬼步伐 19 App->Dialog Dialog样式
这个例子的主Activity定义在AlertDialogSamples.java 主要用来介绍类AlertDialog的用法,AlertDialog提供的功能是多样的: 显示消息给用户,并可提供一到三 ...
- 【起航计划 012】2015 起航计划 Android APIDemo的魔鬼步伐 11 App->Activity->Save & Restore State onSaveInstanceState onRestoreInstanceState
Save & Restore State与之前的例子Android ApiDemo示例解析(9):App->Activity->Persistent State 实现的UI类似,但 ...
- 【起航计划 034】2015 起航计划 Android APIDemo的魔鬼步伐 33 App->Service->Local Service Binding 绑定服务 ServiceConnection Binder
本例和下列Local Service Controller 的Activity代码都定义在LocalServiceActivities.Java 中,作为LocalServiceActivities ...
- 【起航计划 033】2015 起航计划 Android APIDemo的魔鬼步伐 32 App->Service->Foreground Service Controller service使用,共享service,前台服务,onStartCommand
Android系统也提供了一种称为“Service”的组件通常在后台运行.Activity 可以用来启动一个Service,Service启动后可以保持在后台一直运行,即使启动它的Activity退出 ...
- 【起航计划 003】2015 起航计划 Android APIDemo的魔鬼步伐 02 SimpleAdapter,ListActivity,PackageManager参考
01 API Demos ApiDemos 详细介绍了Android平台主要的 API,android 5.0主要包括下图几个大类,涵盖了数百api示例:
随机推荐
- shell-004:检测机器存活或者网络陡动情况!
如下图情况,我们监测的就是此数据,当大于50%了,我们就可以设置告警等! #!/bin/bash # 用ping检测一台机器的存活或者网络波动情况 # 检测机器的丢包率来检测网络波动情况!! n=`p ...
- angularjs指令弹框点击空白处隐藏及常规方法
效果图展示: 第一种方法:angularjs自定义指令: 指令: app.directive('onBlankHide', function () { return { restrict: 'A', ...
- C# 函数参数object sender, EventArgs e
object sender:表示触发事件的控件对象EventArgs e:表示事件数据的类的基类 Windows程序有一个事件机制.用于处理用户事件. 在WinForm中我们经常需要给控件添加事件.例 ...
- day017-------python 类与类的关系
类与类的关系的简单说明 一:类与类的关系 001:依赖关系 002:管理关系 003:继承关系: 二:实例理解: 01:依赖关系: # 植物大战僵尸. 创建一个植物. 创建一个僵尸 # 植物: 名字, ...
- Wannafly挑战赛26-F. msc的棋盘(模型转化+dp)及一类特殊的网络流问题
题目链接 https://www.nowcoder.com/acm/contest/212/F 题解 我们先考虑如果已知了数组 \(\{a_i\}\) 和 \(\{b_i\}\),如何判断其是否合法. ...
- ecshop 模板机制
ECShop模板是基于smarty 文件名cls_template.php lib_main.php中的assign_template()会设置我们的网店的公共信息及网站设置:assign_dynam ...
- HDU 2879 数论
HeHe Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65535/65535 K (Java/Others)Total Submis ...
- PIE SDK矢量数据的投影转换
1. 功能简介 目前在地理信息领域中数据包括矢量和栅格两种数据组织形式 ,每一种数据都可以对投影进行转换,目前PIE SDK支持矢量和栅格数据的投影转换功能,下面对矢量数据的投影转换功能进行介绍. 2 ...
- 4.整体架构和Smart Scan
寻道时间: 外圈,比内圈要多, 即外圈是比较快的. 第一次创建grid disk 时,是创建外圈,用于存放数据的,内圈存储归档这些数据 CellCLI> CREATE GRIDDISK ALL ...
- RabbitMQ原理——exchange、route、queue的关系
从AMQP协议可以看出,MessageQueue.Exchange和Binding构成了AMQP协议的核心,下面我们就围绕这三个主要组件 从应用使用的角度全面的介绍如何利用Rabbit MQ构建 ...