Service的一些迷思

1.爲何調用stopService/unbindService以後Service沒有被銷燬?

經過以前對Service銷燬流程的分析,stopServiceunbindService最終都會進入到ActiveServices.bringDownServiceIfNeededLocked方法中,該方法會判斷當前的Service是否知足銷燬條件,其中的核心方法即是isServiceNeededjava

private final boolean isServiceNeeded(ServiceRecord r, boolean knowConn, boolean hasConn) {
    // Are we still explicitly being asked to run?
    if (r.startRequested) {
        return true;
    }

    // Is someone still bound to us keepign us running?
    if (!knowConn) {
        hasConn = r.hasAutoCreateConnections();
    }
    if (hasConn) {
        return true;
    }

    return false;
}
複製代碼

有兩個很是關鍵的變量:ServiceRecord.startRequestedhasConn,前者與start有關,後者與bind有關,只有二者都爲false才能銷燬一個Service。 咱們先來看看startRequestedapp

ServiceRecord.startRequested

經過全局搜索發現,該字段只有在ActiveServices.startServiceLocked方法中,也便是start流程中會被置爲true。 在ActiveServices.stopServiceLockedActiveServices.stopServiceTokenLockedActiveServices.killServicesLocked這三個方法中會被置爲false,ActiveServices.stopServiceTokenLocked是在Service調用stopSelf時會觸發的,而ActiveServices.killServicesLocked則是在清理應用(內存不足等場景)的時候觸發。函數

簡單來講ServiceRecord.startRequested會在start流程中被置爲true,在stop流程中置爲false。所以,不管你以前調用過多少次startService,只要你調了一次stopService(以後沒有再調用startService),那麼startRequested就被置爲了false。**startRequested的值取決於最後一次調用的是startService仍是stopServicepost

hasConn

該字段的值跟ServiceRecord.hasAutoCreateConnection方法的返回值有關this

public boolean hasAutoCreateConnections() {
    // XXX should probably keep a count of the number of auto-create
    // connections directly in the service.
    for (int conni=connections.size()-1; conni>=0; conni--) {
        ArrayList<ConnectionRecord> cr = connections.valueAt(conni);
        for (int i=0; i<cr.size(); i++) {
            //這個flags就是調用bindService時使用的flags
            if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
                return true;
            }
        }
    }
    return false;
}
複製代碼

該方法內部會遍歷全部bind至當前服務的鏈接,若是還存在任一鏈接,其調用bindService時使用的flags包含BIND_AUTO_CREATE標誌,則返回true,不然返回falsespa

總結

咱們以具體場景來分析怎樣才能銷燬一個服務:code

  1. 只是用了startService來啓動服務。 這種場景下,只須要調用stopService就能夠正常銷燬服務
  2. 只是用了bindService啓動服務 這種場景下,只須要調用對應的unbindService便可、
  3. 同時使用了startServicebindService 這種場景想要關閉服務的話,首先要調用stopService,其次還須要確保以前使用BIND_AUTO_CREATE進行綁定的客戶端解綁(unbindService)便可。

2.爲啥屢次調用bindServcie,而onBind只觸發了一次

Service啓動流程中有一個realStartServiceLocked方法,在服務進程啓動完畢以後,會調用該方法繼續服務啓動的流程。realStartServiceLocked內部調用了一個名爲requestServiceBindingsLocked的方法處理bind請求。從新貼一下該方法代碼:對象

private final void requestServiceBindingsLocked(ServiceRecord r, boolean execInFg) throws TransactionTooLargeException {
    for (int i=r.bindings.size()-1; i>=0; i--) {
        IntentBindRecord ibr = r.bindings.valueAt(i);
        //該方法內部會經過跨進程調用ApplicationThread.scheduleBindService
        //來回調Service.onBind方法
        if (!requestServiceBindingLocked(r, ibr, execInFg, false)) {
            break;
        }
    }
}
複製代碼

能夠看到這裏有一個for循環,這說明了Service.onBind被屢次回調是可能的。那麼問題就變成了ServiceRecord.bindings何時會保存多個值呢? 對bindings字段的put操做只發生在retrieveAppBindingLocked方法中,該方法是在bind流程中的ActiveServices.bindServiceLocked方法中被調用的。 貼下代碼進程

public AppBindRecord retrieveAppBindingLocked(Intent intent,//客戶端發起bind請求所使用的Intent ProcessRecord app) {//客戶端進程記錄
    Intent.FilterComparison filter = new Intent.FilterComparison(intent);
    IntentBindRecord i = bindings.get(filter);
    if (i == null) {
        i = new IntentBindRecord(this, filter);
        bindings.put(filter, i);
    }
    AppBindRecord a = i.apps.get(app);
    if (a != null) {
        return a;
    }
    a = new AppBindRecord(this, i, app);
    i.apps.put(app, a);
    return a;
}
複製代碼

能夠看到該方法首先將intent封裝成了一個FilterComparison對象做爲key,而後去bindings中檢索,若是沒有對應的值就會建立一個值。 再來看看FilterComparison.equals方法,由於只有建立出不一樣的FilterComparison實例,bindings中才會保存多個值。內存

//Intent$FilterComparison.java
public boolean equals(Object obj) {
    if (obj instanceof FilterComparison) {
        Intent other = ((FilterComparison) obj).mIntent;
        return mIntent.filterEquals(other);
    }
    return false;
}

//Intent.java
public boolean filterEquals(Intent other) {
    if (other == null) {
        return false;
    }
    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;
}
複製代碼

能夠看到,FilterComparison的比較實際上是跟Intent密切相關的。Intent內部mActionmDatamTypemPackagemComponentmCategories中的任意字段發生變化,就會產生兩個不一樣的FilterComparison實例。

結論

在調用bindService時,改變一下Intent內部的一些值,就能夠觸發屢次Service.onBind

覆盤

知道告終論,咱們來複盤一下,屢次使用同一個IntentbindService的問題 一般咱們是如下面這種方式來構造Intent

Intent intent = new Intent(activity, DemoService.class);

//Intent.java
public Intent(Context packageContext, Class<?> cls) {
    mComponent = new ComponentName(packageContext, cls);
}
複製代碼

這種方式初始化Intent,最終會將構造函數的入參保存成mComponent

第一次進入bind流程以後,調用retrieveAppBindingLocked確定會爲bindings生成一條新的IntentBindRecord記錄。 這時候若是服務已經啓動,就會立刻進入requestServiceBindingLocked方法

private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i, boolean execInFg, boolean rebind) throws TransactionTooLargeException {
    //...
    //requested此時爲false
    if ((!i.requested || rebind) && i.apps.size() > 0) {
        try {
            //...
            r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,
                    r.app.repProcState);
            if (!rebind) {
                //觸發onBind以後requested被置爲了true
                i.requested = true;
            }
            i.hasBound = true;
            i.doRebind = false;
        } catch (TransactionTooLargeException e) {
            //...
        } catch (RemoteException e) {
            //...
        }
    }
    return true;
}
複製代碼

因而可知,若是使用相同的Intent請求bind,那麼第二次進來requested已是true了,便不會觸發Service.onBind

相關文章
相關標籤/搜索