Compared to AIDL

  When you need to perform IPC, using a Messenger for your interface is simpler than implementing it with AIDL, because Messenger queues all calls to the service, whereas, a pure AIDL interface sends simultaneous requests to the service, which must then handle multi-threading.

  For most applications, the service doesn't need to perform multi-threading, so using a Messenger allows the service to handle one call at a time. If it's important that your service be multi-threaded, then you should use AIDL to define your interface.

Using a Messenger

  If you need your service to communicate with remote processes, then you can use a Messenger to provide the interface for your service. This technique allows you to perform interprocess communication (IPC) without the need to use AIDL.

  Here's a summary of how to use a Messenger:

 使用Messenger的步骤:

  In this way, there are no "methods" for the client to call on the service. Instead, the client delivers "messages" (Message objects) that the service receives in its Handler.

 注意,这种方式下,服务端没有函数给客户端调用。它们只能发送消息。

  Here's a simple example service that uses a Messenger interface:

 public class MessengerService extends Service {
/** Command to the service to display a message */
static final int MSG_SAY_HELLO = ; /**
* Handler of incoming messages from clients.
*/
class IncomingHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_SAY_HELLO:
Toast.makeText(getApplicationContext(), "hello!", Toast.LENGTH_SHORT).show();
break;
default:
super.handleMessage(msg);
}
}
} /**
* Target we publish for clients to send messages to IncomingHandler.
*/
final Messenger mMessenger = new Messenger(new IncomingHandler()); /**
* When binding to the service, we return an interface to our messenger
* for sending messages to the service.
*/
@Override
public IBinder onBind(Intent intent) {
Toast.makeText(getApplicationContext(), "binding", Toast.LENGTH_SHORT).show();
return mMessenger.getBinder();
}
}

  Notice that the handleMessage() method in the Handler is where the service receives the incoming Message and decides what to do, based on the what member.

  All that a client needs to do is create a Messenger based on the IBinder returned by the service and send a message using send(). For example, here's a simple activity that binds to the service and delivers the MSG_SAY_HELLO message to the service:

 public class MessengerActivity extends Activity {
/** Messenger for communicating with the service. */
Messenger mService = null; /** Flag indicating whether we have called bind on the service. */
boolean mBound; /**
* Class for interacting with the main interface of the service.
*/
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with the service has been
// established, giving us the object we can use to
// interact with the service. We are communicating with the
// service using a Messenger, so here we get a client-side
// representation of that from the raw IBinder object.
mService = new Messenger(service);
mBound = true;
} public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
mService = null;
mBound = false;
}
}; public void sayHello(View v) {
if (!mBound) return;
// Create and send a message to the service, using a supported 'what' value
Message msg = Message.obtain(null, MessengerService.MSG_SAY_HELLO, , );
try {
mService.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
} @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_messenger);
} @Override
protected void onStart() {
super.onStart();
// Bind to the service
bindService(new Intent(this, MessengerService.class), mConnection,
Context.BIND_AUTO_CREATE);
} @Override
protected void onStop() {
super.onStop();
// Unbind from the service
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
}

  Notice that this example does not show how the service can respond to the client. If you want the service to respond, then you need to also create a Messenger in the client. Then when the client receives the onServiceConnected() callback, it sends a Message to the service that includes the client's Messenger in the replyTo parameter of the send() method.

  You can see an example of how to provide two-way messaging in the MessengerService.java (service) and MessengerServiceActivities.java (client) samples.

Service官方教程(8)Bound Service示例之2-跨进程使用Messenger的更多相关文章

  1. Service官方教程(11)Bound Service示例之2-AIDL 定义跨进程接口并通信

    Android Interface Definition Language (AIDL) 1.In this document Defining an AIDL Interface Create th ...

  2. Service官方教程(7)Bound Service示例之1-同进程下直接继承Service

    Extending the Binder class If your service is used only by the local application and does not need t ...

  3. Service官方教程(10)Bound Service的生命周期函数

    Managing the Lifecycle of a Bound Service When a service is unbound from all clients, the Android sy ...

  4. Service官方教程(6)Bound Services主要用来实现通信服务,以及3种实现通信的方案简介。

    1.Bound Services A bound service is the server in a client-server interface. A bound service allows ...

  5. Service官方教程(3)Bound Services

    Bound Services 1.In this document The Basics Creating a Bound Service Extending the Binder class Usi ...

  6. Service官方教程(2)*IntentService与Service示例、onStartCommand()3个返回值的含义。

    1.Creating a Started Service A started service is one that another component starts by calling start ...

  7. Service官方教程(1)Started与Bound的区别、要实现的函数、声明service

    Services 简介和分类 A Service is an application component that can perform long-running operations in the ...

  8. Service官方教程(9)绑定服务时的注意事项

    Binding to a Service Application components (clients) can bind to a service by calling bindService() ...

  9. Service官方教程(4)两种Service的生命周期函数

    Managing the Lifecycle of a Service The lifecycle of a service is much simpler than that of an activ ...

随机推荐

  1. 【c++】动态内存

    静态存储区:内存在程序编译的时候就已经分配好,这块内存在程序的整个运行期间都存在.它主要存放静态数据.全局数据和常量.注意:const常量在定义时必须初始化 栈区:在执行函数时,函数内局部变量的存储单 ...

  2. Hexo搭建个人blog

    Hexo搭建 现在只想说心累... 前几天看了几个牛人的blog,感觉他们的风格很舒服,然后就发现了Hexo这个好东西!激动的想马上自己也弄一个,昨天晚上开始看资料特别是:潘柏信写了两篇 HEXO搭建 ...

  3. 学习LaTex

    MarkDown+Latex 本来想学习latex编辑公式的,在博客园内置的MarkDown编辑器已经支持Latex公式解析了,如下: $$x=\frac{-b\pm\sqrt{b^2-4ac}}{2 ...

  4. 一处折腾笔记:Android内嵌html5加入原生微信分享的解决的方法

    有一段时间没有瞎折腾了. 这周一刚上班萌主过来反映说:微信里面打开聚客宝.分享功能是能够的(这里是用微信自身的js-sdk实现的).可是在android应用里面打开点击就没反应了:接下来狡猾的丁丁在产 ...

  5. leetCode 78.Subsets (子集) 解题思路和方法

    Given a set of distinct integers, nums, return all possible subsets. Note: Elements in a subset must ...

  6. Qt实现一个简单的TextEditor

    使用QT实现简单的TextEditor: 首先在窗口添加部件TextEditor,并设置中文字符 MainWindow::MainWindow(QWidget *parent) : QMainWind ...

  7. KindEditor使用过程中,用JQ提交表单时,获取不到编辑器的内容

    首先要说明的是.在使用提交button直接提交时.编辑器的内容是能够正常获取的,而使用 jq或js ,如$("#form").submit(),提交时,则编辑器的内容是无法获取的. ...

  8. 2.NetDh框架之简单高效的日志操作类(附源码和示例代码)

    前言 NetDh框架适用于C/S.B/S的服务端框架,可用于项目开发和学习.目前包含以下四个模块 1.数据库操作层封装Dapper,支持多种数据库类型.多库实例,简单强大: 此部分具体说明可参考博客: ...

  9. 借助ltp语义分析提取特征,之后,文本生成

    """地点-哪里有做-业务-的(正规|靠谱)-公司?地点-做-业务-的(正规|靠谱)-公司(有哪些?|的联系方式是什么?|哪家口碑好值得信赖?)地点-做-业务-(怎么能省 ...

  10. HDU4738 Caocao's Bridges —— 边双联通分量 + 重边

    题目链接:https://vjudge.net/problem/HDU-4738 A network administrator manages a large network. The networ ...