startService和bindService

startService和bindService同时调用后, 必须对应调用stop和unbind,Service才会destroy。

一个已经存活的Service被bind过,然后解绑后重新bind,Service的onBind方法可能不会再次被调用,因为intent相同:

public boolean filterEquals(Intent other) {
        if (other == null) {
            return false;
        }
        // 比较Intent中的各项指标:Action,Uri,MIME type,包名,Component,Category
        if (!Objects.equals(this.mAction, other.mAction)) return false;
        if (!Objects.equals(this.mData, other.mData)) return false;
        if (!Objects.equals(this.mType, other.mType)) return false;
        if (!Objects.equals(this.mPackage, other.mPackage)) return false;
        if (!Objects.equals(this.mComponent, other.mComponent)) return false;
        if (!Objects.equals(this.mCategories, other.mCategories)) return false;

        return true;
    }

官方文档中说,如果多个client绑定服务,那么服务只有在第一次会执行onBind,如下:

如果你的Service被start, 并且被bind,那么当解除所有绑定, 系统调用onUnbind的, 你可以在onUnbind中返回true, 这样你你可以在下次bindService的时候, 可以回调onRebind(不会回调onBind了, 放心吧), onRebind方法返回值void, 但是client仍然可以拿到IBinder对象(这是因为IBind对象被系统缓存起来了),onUnbind中返回false,那么依然会回调onBind.


public interface ServiceConnection {
    /**
     * Called when a connection to the Service has been established, with
     * the {@link android.os.IBinder} of the communication channel to the
     * Service.
     *
     * @param name The concrete component name of the service that has
     * been connected.
     *
     * @param service The IBinder of the Service's communication channel,
     * which you can now make calls on.
     */
    public void onServiceConnected(ComponentName name, IBinder service);

    /**
     * Called when a connection to the Service has been lost.  This typically
     * happens when the process hosting the service has crashed or been killed.
     * This does <em>not</em> remove the ServiceConnection itself -- this
     * binding to the service will remain active, and you will receive a call
     * to {@link #onServiceConnected} when the Service is next running.
     *
     * @param name The concrete component name of the service whose
     * connection has been lost.
     */
    public void onServiceDisconnected(ComponentName name);
}

onServiceDisconnected只有在Service链接异常丢失的时候才会调用,主动unbindService,不会调用onServiceDisconnected。

onServiceConnected和onServiceDisconnected都是在UI线程调用.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值