startService和bindService

xiaoxiao2021-02-28  126

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线程调用.

转载请注明原文地址: https://www.6miu.com/read-35651.html

最新回复(0)