Service之“绑定”

版权声明:本文为博主原创文章,转载请注明原文链接。 https://blog.csdn.net/hao2244/article/details/45201133

    Service类中和Service绑定有关的回调函数有2个:

    1.IBinder onBind(Intent intent);

    该方法的返回值会传递给android.content.ServiceConnection.onServiceConnected(ComponentName name, IBinder service),如果该方法返回值为null,则该Service不能被绑定。

    2.boolean onUnbind(Intent intent);

    在client中可调用的和Service绑定有关的方法有如下2个:

    1.boolean bindService(Intent,ServiceConnection,int);

    2.void unbindService(ServiceConnection);

    这两个方法都定义于android.content.ContextWrapper类(Activity和Service都是ContextWrapper的子类)

    上面提到了一个和Service绑定有关的接口为ServiceConnection,该接口中有两个方法:

    1.void onServiceConnected(ComponentName name, IBinder service);

    该方法在client和service成功建立连接时调用,name参数是所绑定的service的名字,service参数是Service.onBind(Intent intent)所返回的。

    2.void onServiceDisconnected(ComponentName name);

    该方法在client被kill掉时会被调用。注意:当client调用onUnbind(Intent intent)解绑时,该方法不会被调用。

    注意事项:

    1.绑定到service的client有主次之分

       主client是指第一个绑定到该service上的client

       次client是指之后绑定到该service的客户端

        onBind是在主client绑定到该service上时才会调用

        onUnbind是在主client与该service解绑时才会调用,至于在主client解绑之后,Service.onDestroy会不会被调用,取决于该service实例在unbind之前是否通过startService启动过;若是,则不会被调用;若不是,则调用。

    2.绑定service不会调用service.onStartCommand(Intent,int,int);


猜你喜欢

转载自blog.csdn.net/hao2244/article/details/45201133