【起航计划 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示例:
随机推荐
- Qt 学习之路 2(37):文本文件读写
Qt 学习之路 2(37):文本文件读写 豆子 2013年1月7日 Qt 学习之路 2 23条评论 上一章我们介绍了有关二进制文件的读写.二进制文件比较小巧,却不是人可读的格式.而文本文件是一种人可读 ...
- C++_类入门5-智能指针模板类
智能指针是行为类似于指针的类对象,但这种对象还有其他功能. 本节介绍三个可帮助管理动态内存分配的智能指针模板(auto_ptr.unique_ptr和shared_ptr). void remodel ...
- docker image rm ubuntu 失败
[root@hadoop14 ~]# docker image rm ubuntu Failed to remove image (ubuntu:v2): Error response from da ...
- AngularJs--Dependency Injection 规则
参考:https://docs.angularjs.org/guide/di AngularJs的依赖注入简称DI,在AngularJs项目中可以无处不在,到底应该注入些什么东东呢?一直是迷迷糊糊的, ...
- javascript 中typeOf
JS中的变量是松散类型(即弱类型)的,可以用来保存任何类型的数据. typeof 可以用来检测给定变量的数据类型,可能的返回值: 1. 'undefined' --- 这个值未定义: 2. 'bool ...
- [转] DOS命令for用法详解
[From] http://www.jb51.net/article/31284.htm for帮助文档 对一组文件中的每一个文件执行某个特定命令. FOR %variable IN (set) DO ...
- 多租户概念以及FreeLink多租户设计思想
多租户实现思想 多租户技术的实现重点,在于不同租户间应用程序环境的隔离(application context isolation)以及数据的隔离(data isolation),以维持不同租户间应用 ...
- 安装cloudermanager时出现org.spingframework.web.bind.***** host[] is not present at AnnotationMethodHandlerAdapter.java line 738 ****错误(图文详解)(博主推荐)
不多说,直接上干货! 首先,这个问题,写给需要帮助的朋友们,本人在此,搜索资料近半天,才得以解决.看过国内和国外,资料甚少.特此,写此博客,为了弥补此错误解决的资料少的缘故! 问题详解 解决办法 ...
- 信号和槽:Qt中最差劲的创造
不要被这个标题唬住了,实际上我是非常认可Qt的.在C++实现的开源产品中没有哪一个的API风格比得上Qt,拥有高度一致性,符合常识,符合直觉,几乎不用学就可以直接上手.或许是由于我们摆脱不了马太效应的 ...
- unity 移动物体到指定位置的四种方法 【精确移动到指定位置,再也不是计算距离了,物体可以高速移动】
方法1:使用Vector3.MoveTowards </pre><pre name="code" class="csharp">void ...