今天讲绑定服务的具体步骤,比较简单,因为之前几节已经讲解了绑定服务的3种方法,在其中的第一种方法中提到了通过Binder方式绑定服务的步骤。
绑定到服务
应用组件(客户端)可通过调用 bindService() 绑定到服务。Android 系统随后调用服务的 onBind() 方法,该方法返回用于与服务交互的 IBinder。
绑定是异步的。bindService() 会立即返回,“不会”使 IBinder 返回客户端。要接收 IBinder,客户端必须创建一个 ServiceConnection 实例,并将其传递给 bindService()。ServiceConnection 包括一个回调方法,系统通过调用它来传递 IBinder。
注:只有 Activity、服务和内容提供程序可以绑定到服务 — 您无法从广播接收器绑定到服务。
因此,要想从您的客户端绑定到服务,您必须:
- 实现 ServiceConnection。
您的实现必须重写两个回调方法:
onServiceConnected()
系统会调用该方法以传递服务的 onBind() 方法返回的 IBinder。
onServiceDisconnected()
Android 系统会在与服务的连接意外中断时(例如当服务崩溃或被终止时)调用该方法。当客户端取消绑定时,系统“不会”调用该方法。
- 调用 bindService(),传递 ServiceConnection 实现。
- 当系统调用您的 onServiceConnected() 回调方法时,您可以使用接口定义的方法开始调用服务。
- 要断开与服务的连接,请调用 unbindService()。
例如,以下代码段通过扩展 Binder 类将客户端与上面创建的服务相连,因此它只需将返回的 IBinder 转换为 LocalService 类并请求 LocalService 实例:
LocalService mService;
private ServiceConnection mConnection = new ServiceConnection() {
// Called when the connection with the service is established
public void onServiceConnected(ComponentName className, IBinder service) {
// Because we have bound to an explicit
// service that is running in our own process, we can
// cast its IBinder to a concrete class and directly access it.
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
}
// Called when the connection with the service disconnects unexpectedly
public void onServiceDisconnected(ComponentName className) {
Log.e(TAG, "onServiceDisconnected");
mBound = false;
}
};
客户端可通过将此 ServiceConnection 传递至 bindService() 绑定到服务。例如:
Intent intent = new Intent(this, LocalService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
- bindService() 的第一个参数是一个 Intent,用于显式命名要绑定的服务(但 Intent 可能是隐式的)
- 第二个参数是 ServiceConnection 对象
- 第三个参数是一个指示绑定选项的标志。它通常应该是 BIND_AUTO_CREATE,以便创建尚未激活的服务。其他可能的值为 BIND_DEBUG_UNBIND 和 BIND_NOT_FOREGROUND,或 0(表示无)。