Service官方教程(7)Bound Service示例之1-同进程下直接继承Service
Extending the Binder class
If your service is used only by the local application and does not need to work across processes, then you can implement your own Binder class that provides your client direct access to public methods in the service.
Note: This works only if the client and service are in the same application and process, which is most common. For example, this would work well for a music application that needs to bind an activity to its own service that's playing music in the background.
Here's how to set it up:步骤如下
- In your service, create an instance of
Binderthat either:- contains public methods that the client can call
- returns the current
Serviceinstance, which has public methods the client can call - or, returns an instance of another class hosted by the service with public methods the client can call
- Return this instance of
Binderfrom theonBind()callback method. - In the client, receive the
Binderfrom theonServiceConnected()callback method and make calls to the bound service using the methods provided.
Note: The reason the service and client must be in the same application is so the client can cast the returned object and properly call its APIs. The service and client must also be in the same process, because this technique does not perform any marshalling across processes.
For example, here's a service that provides clients access to methods in the service through a Binder implementation:
public class LocalService extends Service {
// Binder given to clients
private final IBinder mBinder = new LocalBinder();
// Random number generator
private final Random mGenerator = new Random();
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
LocalService getService() {
// Return this instance of LocalService so clients can call public methods
return LocalService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
/** method for clients */
public int getRandomNumber() {
return mGenerator.nextInt();
}
}
The LocalBinder provides the getService() method for clients to retrieve the current instance of LocalService. This allows clients to call public methods in the service. For example, clients can call getRandomNumber() from the service.
Here's an activity that binds to LocalService and calls getRandomNumber() when a button is clicked:
public class BindingActivity extends Activity {
LocalService mService;
boolean mBound = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_binding);
}
@Override
protected void onStart() {
super.onStart();
// Bind to LocalService
Intent intent = new Intent(this, LocalService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
// Unbind from the service
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
/** Called when a button is clicked (the button in the layout file attaches to
* this method with the android:onClick attribute) */
public void onButtonClick(View v) {
if (mBound) {
// Call a method from the LocalService.
// However, if this call were something that might hang, then this request should
// occur in a separate thread to avoid slowing down the activity performance.
int num = mService.getRandomNumber();
Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show();
}
}
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className,
IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
LocalService.LocalBinder binder = (LocalService.LocalBinder) service;
mService = binder.getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
}
The above sample shows how the client binds to the service using an implementation of ServiceConnection and the onServiceConnected() callback. The next section provides more information about this process of binding to the service.
Note: In the example above, the onStop() method unbinds the client from the service. Clients should unbind from services at appropriate times, as discussed in Additional Notes.
For more sample code, see the LocalService.java class and the LocalServiceActivities.java class in ApiDemos.
Service官方教程(7)Bound Service示例之1-同进程下直接继承Service的更多相关文章
- Service官方教程(8)Bound Service示例之2-跨进程使用Messenger
Compared to AIDL When you need to perform IPC, using a Messenger for your interface is simpler than ...
- 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官方教程(11)Bound Service示例之2-AIDL 定义跨进程接口并通信
Android Interface Definition Language (AIDL) 1.In this document Defining an AIDL Interface Create th ...
- Service官方教程(10)Bound Service的生命周期函数
Managing the Lifecycle of a Bound Service When a service is unbound from all clients, the Android sy ...
- 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 ...
随机推荐
- 报错** is not accessible due to restriction on required library
报错: Description Resource Path Location TypeAccess restriction: The type Map<String,Object> is ...
- 异或巧用:Single Number
异或巧用:Single Number 今天刷leetcode,碰到了到题Single Number.认为解答非常巧妙,故记之... 题目: Given an array of integers, ev ...
- LoadRunner压测时,出现的问题汇总
[问题]Error -10776 Failed to find .cfg file 错误分析:在loadrunner打开脚本的情况下,运行磁盘清理工具,导致运行打开的脚本时,提示Mdrv error ...
- UIButton的图片和文字相对位置调整
通常.假设直接设置UIButton的图片和文字,默认的两者相对位置可能不是我们想要的,那么须要进行调整. 须要用到的函数例如以下: UIEdgeInsetsMake(CGFloat top, CGFl ...
- Linux常用服务安装部署
1,centos7默认是装有python的,检查python版本的命令 # 检查python版本 : python -V 2,centOS在安装python3以及tab补全功能 下载python3源码 ...
- Spring如何实现IOC和AOP的,说出实现原理。
用过spring的朋友都知道spring的强大和高深,都觉得深不可测,其实当你真正花些时间读一读源码就知道它的一些技术实现其实是建立在一些最基本的技术之上而已:例如AOP(面向方面编程)的实现是建立在 ...
- HTTP要点概述:一,TCP/IP协议族
一,协议: 计算机与网络设备之间如果要相互通信,双方必须基于相同的方法.比如说,怎么探测到通讯目标,哪一方发起通信,使用哪一种语言通信,怎么结束通信,都需要事先规定.不同硬件,操作系统之间的通信需要一 ...
- 搭建基于Maven的SSM框架
先展示文件结构图对工程结构有大致了解: 主要为 ssm-parent (用来管理jar包版本)是每个工程的父工程,ssm-common(用来处理底层数据),ssm-manager(对数据库信息进行操 ...
- java操作CMD命令
import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; public class CM ...
- HDU4081 Qin Shi Huang's National Road System —— 次小生成树变形
题目链接:https://vjudge.net/problem/HDU-4081 Qin Shi Huang's National Road System Time Limit: 2000/1000 ...