文中的源代碼版本爲api23java
流程簡圖以下api
關閉Service咱們一般使用Context.stopService
,該方法會經歷如下方法調用
Context.stopService
->
ContextImpl.stopService
->
ContextImpl.stopServiceCommon
->
ActivityManagerService.stopServcie
->
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
繼續下面的流程,該方法內部直接調用了bringDownServiceIfNeededLocked
app
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
isServiceNeeded
方法判斷服務是否還有必要存在,若是有則直接返回bringDownServiceLocked
繼續中止服務的流程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
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
ServiceConnection.onServiceDisconnected
onUnbind
生命週期方法onDestory
生命週期方法此時服務就真正走向了生命的終點了。rest
流程簡圖以下code
Context.unbindService
方法會經歷如下調用鏈 Context.unbindService
-> ContextImpl.unbindService
-> ActivityManagerService.unbindService
-> ActiveService.unbindServiceLocked
cdn
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
這邊就會保存多個ConnectionRecord
。 unbindServiceLocked
內使用了一個while
循環,依次對每一個ConnectionRecord
調用removeConnectionLocked
。blog
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
hasAutoCreateConnections
和bringDownServiceIfNeededLocked
方法咱們在分析stopService
流程的時候已經分析過了,就不展開講了,這裏只討論bringDownServiceIfNeededLocked
入參變化而引發的一些變化。 假設當前沒有其餘客戶端綁定至該服務,那麼此時hasAutoCreate
應該爲false
,那麼bringDownServiceIfNeededLocked
的形參,knowConn
爲true
,hasConn
爲false
這兩個參數,只會在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
的同樣了。