Service銷燬流程

文中的源代碼版本爲api23java

Service銷燬流程

stopService流程

流程簡圖以下api

關閉Service咱們一般使用 Context.stopService,該方法會經歷如下方法調用 Context.stopService-> ContextImpl.stopService-> ContextImpl.stopServiceCommon-> ActivityManagerService.stopServcie-> ActiveServcie.stopServiceLocked

ActiveServcie.stopServiceLocked

int stopServiceLocked(IApplicationThread caller, Intent service, String resolvedType, int userId) {
    //...

    // If this service is active, make sure it is stopped.
    ServiceLookupResult r = retrieveServiceLocked(service, resolvedType, null,
            Binder.getCallingPid(), Binder.getCallingUid(), userId, false, false);
    if (r != null) {
        if (r.record != null) {
            final long origId = Binder.clearCallingIdentity();
            try {
                stopServiceLocked(r.record);
            } finally {
                Binder.restoreCallingIdentity(origId);
            }
            return 1;
        }
        return -1;
    }

    return 0;
}

private void stopServiceLocked(ServiceRecord service) {
    //...
    //設置startRequested爲false,在後面的流程中有用
    service.startRequested = false;
    //...
    service.callStart = false;
    bringDownServiceIfNeededLocked(service, false, false);
}

複製代碼

該方法邏輯比較簡單,經過retrieveServiceLocked方法找到服務記錄,而後調用重載方法stopServiceLocked繼續下面的流程,該方法內部直接調用了bringDownServiceIfNeededLockedapp

ActiveServices.bringDownServiceIfNeededLocked

private final void bringDownServiceIfNeededLocked(ServiceRecord r, boolean knowConn/*false*/, boolean hasConn/*false*/) {

    //...

    //判斷是否有bind
    if (isServiceNeeded(r, knowConn, hasConn)) {
        return;
    }

    // Are we in the process of launching?
    if (mPendingServices.contains(r)) {
        return;
    }

    bringDownServiceLocked(r);
}
複製代碼

該方法作了三件事情this

  1. 調用isServiceNeeded方法判斷服務是否還有必要存在,若是有則直接返回
  2. 查看服務是否存在於待啓動服務列表中,若是是則直接返回
  3. 上面的條件都不知足的話則會調用bringDownServiceLocked繼續中止服務的流程
ActiveServices.isServiceNeeded
private final boolean isServiceNeeded(ServiceRecord r, boolean knowConn, boolean hasConn) {
    // 該字段在stopServiceLocked方法中已經被置爲false
    if (r.startRequested) {
        return true;
    }

    // knowConn此時爲false,因此會走這個if流程
    if (!knowConn) {
        hasConn = r.hasAutoCreateConnections();
    }
    if (hasConn) {
        return true;
    }

    return false;
}

//ServiceRecord.java
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++) {
            if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
                return true;
            }
        }
    }
    return false;
}
複製代碼

isServiceNeeded內部又調用了hasAutoCreateConnections hasAutoCreateConnections會檢測當前服務的綁定記錄(bindService記錄),在這些記錄中只要有使用了帶有BIND_AUTO_CREATE標誌的Intent則返回true,表示不容許關閉服務。從這點能夠看出,調用stopService以後並不必定會真正的關閉服務。 假設服務未被綁定,咱們繼續下面的流程spa

ActiveServices.bringDownServiceLocked

private final void bringDownServiceLocked(ServiceRecord r) {

    for (int conni=r.connections.size()-1; conni>=0; conni--) {
        ArrayList<ConnectionRecord> c = r.connections.valueAt(conni);
        for (int i=0; i<c.size(); i++) {
            ConnectionRecord cr = c.get(i);
            cr.serviceDead = true;
            try {
                //斷開客戶端鏈接
                //經過IPC觸發ServiceConnectino.onServiceDisconnected
                cr.conn.connected(r.name, null);
            } catch (Exception e) {
                //...
            }
        }
    }


    if (r.app != null && r.app.thread != null) {
        for (int i=r.bindings.size()-1; i>=0; i--) {
            IntentBindRecord ibr = r.bindings.valueAt(i);
            //...
            if (ibr.hasBound) {
                try {
                    //...
                    ibr.hasBound = false;
                    //經過IPC觸發Service.onUnbind方法
                    r.app.thread.scheduleUnbindService(r,
                            ibr.intent.getIntent());
                } catch (Exception e) {
                    //...
                }
            }
        }
    }

    //...

    //清理服務記錄
    final ServiceMap smap = getServiceMap(r.userId);
    smap.mServicesByName.remove(r.name);
    smap.mServicesByIntent.remove(r.intent);
    r.totalRestartCount = 0;
    unscheduleServiceRestartLocked(r, 0, true);

    //從待啓動流程中移除
    for (int i=mPendingServices.size()-1; i>=0; i--) {
        if (mPendingServices.get(i) == r) {
            mPendingServices.remove(i);
            if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Removed pending: " + r);
        }
    }

    //...

    //一些清理工做
    r.clearDeliveredStartsLocked();
    r.pendingStarts.clear();

    if (r.app != null) {
        //...
        r.app.services.remove(r);
        if (r.app.thread != null) {
            //...
            try {
                //...
                mDestroyingServices.add(r);
                r.destroying = true;
                mAm.updateOomAdjLocked(r.app);
                //經過IPC觸發Service.onDestory
                r.app.thread.scheduleStopService(r);
            } catch (Exception e) {
                //...
            }
        } else {
            //...
        }
    } else {
        //...
    }

    //...
}

複製代碼

中止服務的邏輯仍是挺清晰的3d

  1. 關閉全部的客戶端鏈接,這個階段就是經過IPC觸發客戶端的ServiceConnection.onServiceDisconnected
  2. 經過IPC觸發服務的onUnbind生命週期方法
  3. 清理一些資源
  4. 經過IPC觸發服務的onDestory生命週期方法

此時服務就真正走向了生命的終點了。rest

unbindService流程

流程簡圖以下code

Context.unbindService方法會經歷如下調用鏈 Context.unbindService-> ContextImpl.unbindService-> ActivityManagerService.unbindService-> ActiveService.unbindServiceLockedcdn

ActiveService.unbindServiceLocked

boolean unbindServiceLocked(IServiceConnection connection) {
    //對應於客戶端的ServiceConnection
    IBinder binder = connection.asBinder();

    //可使用同一個ServiceConnection鏈接多個Service
    //所以這裏拿出來是一個List
    ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
    //...

    final long origId = Binder.clearCallingIdentity();
    try {
        while (clist.size() > 0) {
            ConnectionRecord r = clist.get(0);
            removeConnectionLocked(r, null, null);
            //...
        }
    } finally {
        Binder.restoreCallingIdentity(origId);
    }

    return true;
}
複製代碼

客戶端的一個ServiceConnection實例能夠bind至多個Service,對應於AMS這邊就會保存多個ConnectionRecordunbindServiceLocked內使用了一個while循環,依次對每一個ConnectionRecord調用removeConnectionLockedblog

ActiveServices.removeConnectionLocked

void removeConnectionLocked( ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
    IBinder binder = c.conn.asBinder();
    AppBindRecord b = c.binding;
    ServiceRecord s = b.service;
    //移除ServiceRecord以及客戶端ProcessRecord等內部維護的
    //ConnectionRecord
    ArrayList<ConnectionRecord> clist = s.connections.get(binder);
    if (clist != null) {
        clist.remove(c);
        if (clist.size() == 0) {
            s.connections.remove(binder);
        }
    }
    b.connections.remove(c);
    if (c.activity != null && c.activity != skipAct) {
        if (c.activity.connections != null) {
            c.activity.connections.remove(c);
        }
    }
    if (b.client != skipApp) {
        b.client.connections.remove(c);
        //...
    }
    clist = mServiceConnections.get(binder);
    if (clist != null) {
        clist.remove(c);
        if (clist.size() == 0) {
            mServiceConnections.remove(binder);
        }
    }

    //...

    if (b.connections.size() == 0) {
        b.intent.apps.remove(b.client);
    }
    //此處serviceDead爲false
    if (!c.serviceDead) {
        //...
        if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
                && b.intent.hasBound) {
            try {
                //...
                b.intent.hasBound = false;
                // Assume the client doesn't want to know about a rebind;
                // we will deal with that later if it asks for one.
                b.intent.doRebind = false;
                s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
            } catch (Exception e) {
                Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
                serviceProcessGoneLocked(s);
            }
        }

        //這個flags就是調用bindService時用的flags
        if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
            boolean hasAutoCreate = s.hasAutoCreateConnections();
            //...
            bringDownServiceIfNeededLocked(s, true, hasAutoCreate);
        }
    }
}
複製代碼

removeConnectionLocked首先會作一些清理工做,以後會調用ApplicationThread.scheduleUnbindService方法觸發Service.onUnbind 其次,若是發起bind請求時所用的flags中包含BIND_AUTO_CREATE標誌,還會觸發bringDownServiceIfNeededLocked hasAutoCreateConnectionsbringDownServiceIfNeededLocked方法咱們在分析stopService流程的時候已經分析過了,就不展開講了,這裏只討論bringDownServiceIfNeededLocked入參變化而引發的一些變化。 假設當前沒有其餘客戶端綁定至該服務,那麼此時hasAutoCreate應該爲false,那麼bringDownServiceIfNeededLocked的形參,knowConntruehasConnfalse 這兩個參數,只會在bringDownServiceIfNeededLocked內調用isServiceNeeded方法使用到,再貼一下這個方法的代碼

private final boolean isServiceNeeded(ServiceRecord r, boolean knowConn/*true*/, boolean hasConn/*false*/) {
    // startRequested只有在調用過startService纔會被置爲true
    // 這裏爲false
    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;
}
複製代碼

能夠看到isServiceNeeded此時返回false,所以銷燬的流程還會繼續進行下去。 後續的流程就跟stopService的同樣了。

相關文章
相關標籤/搜索