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
Handlerthat receives a callback for each call from a client. - The
Handleris used to create aMessengerobject (which is a reference to theHandler). - The
Messengercreates anIBinderthat the service returns to clients fromonBind(). - Clients use the
IBinderto instantiate theMessenger(that references the service'sHandler), which the client uses to sendMessageobjects to the service. - The service receives each
Messagein 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 ...
随机推荐
- 【c++】动态内存
静态存储区:内存在程序编译的时候就已经分配好,这块内存在程序的整个运行期间都存在.它主要存放静态数据.全局数据和常量.注意:const常量在定义时必须初始化 栈区:在执行函数时,函数内局部变量的存储单 ...
- Python常用的几种常用的内置函数
abs(x) 用于返回绝对值 divmod(x,y) 函数中传入两个数字,返回的是x/y的一个结果的元组(商,余数) pow(x,y) 用于 ...
- aix用户登录次数受限问题(3004-300 输入了无效的登录名或password)
当登录AIX系统.username或password不对以至于多次登录,超过系统设定的次数,怎样解锁: 1.用root用户登录系统 2.chuser unsuccessful_login_count= ...
- BZOJ1087=Codevs2451=洛谷P1896&P2326互不侵犯
1087: [SCOI2005]互不侵犯King Time Limit: 10 Sec Memory Limit: 162 MBSubmit: 2885 Solved: 1693[Submit][ ...
- NYOJ110 剑客决斗
剑客决斗 来源:Polish Olympiad in Informatics(波兰信息学奥林匹克竞赛) 时间限制:5000 ms | 内存限制:65535 KB 难度:5 描述 在路易十三和红 ...
- EJB3.0
由于EJB2.0的复杂性,在Spring和Hibernate[1] 等轻量级框架出现后,大量的用户转向应用轻量级框架.在大家的呼声中, EJB 期待已久的EJB3.0规范终于发布了.在本文中将对新的 ...
- XML简单介绍及举例
可扩展标记语言(eXtensibleMarkup Language,简称XML).是一种标记语言.标记指计算机所能理解的信息符号.通过此种标记,计算机之间能够处理包括各种信息的文章等. 怎样定义这些标 ...
- 2.7 xargs和exec详解【转】
本文转载自:http://ask.apelearn.com/question/13323 常用在查找中exec主要是和find一起配合使用,而xargs就要比exec用的地方要多了. exec 应用 ...
- 第一个Java程序示例——Hello World!【转】
本文转载自: 跟随世界潮流,第一个Java程序输出“Hell World!”. 通过Eclipse运行程序 启动Eclipse,在菜单中选择“文件 --> 新建 --> Java项目”,弹 ...
- java抛出异常后,后续代码是否可继续执行
参考:https://www.cnblogs.com/wangyingli/p/5912269.html 仅此可正常执行异常后内容 try{ throw new Exception("参数越 ...