前面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实现进程间通信的更多相关文章

  1. 【起航计划 002】2015 起航计划 Android APIDemo的魔鬼步伐 01

    本文链接:[起航计划 002]2015 起航计划 Android APIDemo的魔鬼步伐 01 参考链接:http://blog.csdn.net/column/details/mapdigitap ...

  2. 【起航计划 037】2015 起航计划 Android APIDemo的魔鬼步伐 36 App->Service->Remote Service Binding AIDL实现不同进程间调用服务接口 kill 进程

    本例和下个例子Remote Service Controller 涉及到的文件有RemoteService.java ,IRemoteService.aidl, IRemoteServiceCallb ...

  3. 【起航计划 031】2015 起航计划 Android APIDemo的魔鬼步伐 30 App->Preferences->Advanced preferences 自定义preference OnPreferenceChangeListener

    前篇文章Android ApiDemo示例解析(31):App->Preferences->Launching preferences 中用到了Advanced preferences 中 ...

  4. 【起航计划 027】2015 起航计划 Android APIDemo的魔鬼步伐 26 App->Preferences->Preferences from XML 偏好设置界面

    我们在前面的例子Android ApiDemo示例解析(9):App->Activity->Persistent State 介绍了可以使用Shared Preferences来存储一些状 ...

  5. 【起航计划 020】2015 起航计划 Android APIDemo的魔鬼步伐 19 App->Dialog Dialog样式

    这个例子的主Activity定义在AlertDialogSamples.java 主要用来介绍类AlertDialog的用法,AlertDialog提供的功能是多样的: 显示消息给用户,并可提供一到三 ...

  6. 【起航计划 012】2015 起航计划 Android APIDemo的魔鬼步伐 11 App->Activity->Save & Restore State onSaveInstanceState onRestoreInstanceState

    Save & Restore State与之前的例子Android ApiDemo示例解析(9):App->Activity->Persistent State 实现的UI类似,但 ...

  7. 【起航计划 034】2015 起航计划 Android APIDemo的魔鬼步伐 33 App->Service->Local Service Binding 绑定服务 ServiceConnection Binder

    本例和下列Local Service Controller 的Activity代码都定义在LocalServiceActivities.Java 中,作为LocalServiceActivities ...

  8. 【起航计划 033】2015 起航计划 Android APIDemo的魔鬼步伐 32 App->Service->Foreground Service Controller service使用,共享service,前台服务,onStartCommand

    Android系统也提供了一种称为“Service”的组件通常在后台运行.Activity 可以用来启动一个Service,Service启动后可以保持在后台一直运行,即使启动它的Activity退出 ...

  9. 【起航计划 003】2015 起航计划 Android APIDemo的魔鬼步伐 02 SimpleAdapter,ListActivity,PackageManager参考

    01 API Demos ApiDemos 详细介绍了Android平台主要的 API,android 5.0主要包括下图几个大类,涵盖了数百api示例:

随机推荐

  1. Android与MVC设计模式

    写在前面,之前做过一段时间移动开发,后来因为工作原因搁浅了,最新重新拿起Android权威编程指南学习,顺道做个学习笔记. 首先呢,我想说无论是计算机科班出身还是培训班出身,都听说过高内聚低耦合以及M ...

  2. Flask之flask-migrate 数据库迁移

    简介 flask-migrate是flask的一个扩展模块,主要是扩展数据库表结构的. 官方文档:http://flask-migrate.readthedocs.io/en/latest/ 使用fl ...

  3. js实现点击按钮滚动条缓慢滚动到顶部

    toTop:function(){ //toTop 滚动到顶部 var currentPosition,timer; var speed=10; timer=setInterval(function( ...

  4. SSH 项目建立过程

    1. 加入 Spring 1). 加入 jar 包 2). 配置 web.xml 文件 <context-param> <param-name>contextConfigLoc ...

  5. [转] 商业应用中Java浮点数的精确计算及表示

    [From] https://blog.csdn.net/stevene/article/details/586089 问题提出 (1).浮点数精确计算 胜利油田三流合一项目中一直存在一个问题,就是每 ...

  6. C++ GUI Qt4编程(13)-6.2preferencedialog

    1. 主要介绍了QStackedLayout.QListWidget.QDialogButtonBox的简单用法.2. QStackedLayout:   要使某个特定的子窗口部件可见,可以用setC ...

  7. C++ GUI Qt4编程(07)-3.1menu

    1. C++ GUI Qt4编程第三章,添加menu菜单. 2. mainwindow.h #ifndef MAINWINDOW_H #define MAINWINDOW_H #include < ...

  8. linux 密码复杂度设置

    /etc/login.defs文件,里面几个选项 PASS_MAX_DAYS 90 #密码最长过期天数 PASS_MIN_DAYS 80 #密码最小过期天数 PASS_MIN_LEN 10 #密码最小 ...

  9. mysql DQL语言操作

    SQL语句的执行顺序:from-where-group by-having-select-order by where 可以筛选多个条件,如 where  A and B 1.排序order by 列 ...

  10. NodeJS 实现阿里云推送。

    虽然阿里云推送也有 NodeJS SDK ,只要在项目中引用 aliyun-sdk 就可以使用了.里面的推送功能了. 我在这里就不写怎么使用aliyun-sdk.给出来的DEMO是回调形式的.用起来有 ...