android developer tiny share-20170210

今天讲绑定服务的具体步骤,比较简单,因为之前几节已经讲解了绑定服务的3种方法,在其中的第一种方法中提到了通过Binder方式绑定服务的步骤。


绑定到服务


应用组件(客户端)可通过调用 bindService() 绑定到服务。Android 系统随后调用服务的 onBind() 方法,该方法返回用于与服务交互的 IBinder。

绑定是异步的。bindService() 会立即返回,“不会”使 IBinder 返回客户端。要接收 IBinder,客户端必须创建一个 ServiceConnection 实例,并将其传递给 bindService()。ServiceConnection 包括一个回调方法,系统通过调用它来传递 IBinder。

注:只有 Activity、服务和内容提供程序可以绑定到服务 — 您无法从广播接收器绑定到服务。

因此,要想从您的客户端绑定到服务,您必须:

  1. 实现 ServiceConnection。
    您的实现必须重写两个回调方法:
    onServiceConnected()
            系统会调用该方法以传递服务的 onBind() 方法返回的 IBinder。
    onServiceDisconnected()
            Android 系统会在与服务的连接意外中断时(例如当服务崩溃或被终止时)调用该方法。当客户端取消绑定时,系统“不会”调用该方法。
  2. 调用 bindService(),传递 ServiceConnection 实现。
  3. 当系统调用您的 onServiceConnected() 回调方法时,您可以使用接口定义的方法开始调用服务。
  4. 要断开与服务的连接,请调用 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(表示无)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值