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. 【转】Web Worker javascript多线程编程(一)

    原文:https://www.cnblogs.com/peakleo/p/6218823.html -------------------------------------------------- ...

  2. Office EXCEL 中单元格怎么打斜线

    右击单元格,然后设置单元格格式,然后添加需要的边框     注意里面的文字有讲究,比如我要右上角显示Value,左下角显示Payload,则需要先输一堆空格,然后输入Value,把Value挤到右边去 ...

  3. Mongodb for PHP教程之数据操作

    Mongodb的常用操作 参看手册,php官方的http://us2.php.net/manual/en/mongo.manual.php 也可以参看mongodb官方的教程 数据库连接 ⑴默认格式 ...

  4. MySQL存储结构的使用

    前言 今天公司老大让我做一个MySQL的调研工作,是关于MySQL的存储结构的使用.这里我会通过3个样例来介绍一下MySQL中存储结构的使用过程,以及一些须要注意的点. 笔者环境 系统:Windows ...

  5. Codeforces466C Number of Ways

    题目链接: http://codeforces.com/problemset/problem/466/C 题意: 给一个长度为n的数组,将其分成连续的三段使三段的和相等.求有几种这种组合 分析: 从头 ...

  6. Pierce振荡器设计

    一.Pierce振荡器电路 Inv:内部反相器,作用等同于放大器: Q:石英晶体或陶瓷晶振: RF:内部反馈电阻(使反相器工作在线性区): RExt:外部限流电阻(防止石英晶体被过分驱动): CL1. ...

  7. Windows下编译DCMTK

    原帖地址:http://www.cnblogs.com/yinxufeng/p/3636241b7084b0340cc56fd37f9e2fd8.html 下载源码生成VS项目工程编译源码 下载源码 ...

  8. 2016/2/25 onchange 应用

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  9. IDEA 使用方法快捷键

    Ctrl+Shift + Enter,语句完成“!”,否定完成,输入表达式时按 “!”键Ctrl+E,最近的文件Ctrl+Shift+E,最近更改的文件Shift+Click,可以关闭文件Ctrl+[ ...

  10. Oracle修改序列(Sequence)起始值问题

    Oracle 序列(Sequence)主要用于生成流水号,在应用中经常会用到,特别是作为ID值,拿来做表主键使用较多. 但是,有时需要修改序列初始值(START WITH)时,有同仁使用这个语句来修改 ...