Service官方教程(8)Bound Service示例之2-跨进程使用Messenger
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的步骤:
- The service implements a
Handler
that receives a callback for each call from a client. - The
Handler
is used to create aMessenger
object (which is a reference to theHandler
). - The
Messenger
creates anIBinder
that the service returns to clients fromonBind()
. - Clients use the
IBinder
to instantiate theMessenger
(that references the service'sHandler
), which the client uses to sendMessage
objects to the service. - The service receives each
Message
in itsHandler
—specifically, in thehandleMessage()
method.
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的更多相关文章
- Service官方教程(11)Bound Service示例之2-AIDL 定义跨进程接口并通信
Android Interface Definition Language (AIDL) 1.In this document Defining an AIDL Interface Create th ...
- 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 ...
- Service官方教程(10)Bound Service的生命周期函数
Managing the Lifecycle of a Bound Service When a service is unbound from all clients, the Android sy ...
- Service官方教程(6)Bound Services主要用来实现通信服务,以及3种实现通信的方案简介。
1.Bound Services A bound service is the server in a client-server interface. A bound service allows ...
- Service官方教程(3)Bound Services
Bound Services 1.In this document The Basics Creating a Bound Service Extending the Binder class Usi ...
- Service官方教程(2)*IntentService与Service示例、onStartCommand()3个返回值的含义。
1.Creating a Started Service A started service is one that another component starts by calling start ...
- Service官方教程(1)Started与Bound的区别、要实现的函数、声明service
Services 简介和分类 A Service is an application component that can perform long-running operations in the ...
- Service官方教程(9)绑定服务时的注意事项
Binding to a Service Application components (clients) can bind to a service by calling bindService() ...
- Service官方教程(4)两种Service的生命周期函数
Managing the Lifecycle of a Service The lifecycle of a service is much simpler than that of an activ ...
随机推荐
- axis client tomcat jsp调用最少jar
tomcat调用和main方法调用不同在于引入的jar不一样.tomcat引入的jar是全部lib以下的jar包,main是project引入的jar.假设直接进行公布lib下的全部jar都会引入到p ...
- Linux文件系统与磁盘管理
Linux文件系统与磁盘管理 有哪些文件系统: FAT:微软在Dos/Windows系列操作系统中共使用的一种文件系统的总称. exFAT(Extended File Allocation ...
- ffmpeg转码本地文件(一)
ffmpeg转码本地文件(一) 实现目标:输入本地文件.实现本地文件转码,里面包括mux层转码,codec层转码,视频格式转换,音频重採样等功能,功能点请看凝视.注意:凝视非常重要. #ifndef ...
- Django的缓存,序列化,ORM操作的性能
1,缓存:把数据先保存在某个地方,下次再读取的时候不用再去原位置读取
- 自己写好的pdo数据库抽象层 mysql为例
版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/qq1355541448/article/details/31787719 class pdo_dat ...
- html页面缓存问题
若IIS没有设置,html页面一旦缓存,则永远缓存. Chrome如下 火狐如下 一种方法:我们一般通过xxx.html?20151010这样URL欺骗浏览器. 另一种方法:设置IIS,让永远客户端不 ...
- RabbitMQ(三)RabbitMQ消息过期时间(TTL)
在RabbitMQ(二)AMQP协议mandatory和immediate标志位区别中我们提到,在RabbitMQ3.0以后的版本里,去掉了immediate参数支持,要实现类似的确认功能要使用TTL ...
- 一步一步学Silverlight 2系列(4):鼠标事件处理
一步一步学Silverlight 2系列(4):鼠标事件处理 概述 Silverlight 2 Beta 1版本发布了,无论从Runtime还是Tools都给我们带来了很多的惊喜,如支持框架语言V ...
- 输出两个MAC地址之间的地址
/******************************************************************************* * 输出两个MAC地址之间的地址 * ...
- 【HAOI 2007】 上升序列
[题目链接] 点击打开链接 [算法] 先预处理 : 将序列反转,求最长下降子序列 对于每个询问,根据字典序性质,贪心即可 [代码] #include<bits/stdc++.h> usin ...