Android Service綁定過程完整分析
通常我們使用Service都要和它通信,當(dāng)想要與Service通信的時(shí)候,那么Service要處于綁定狀態(tài)的。然后客戶端可以拿到一個(gè)Binder與服務(wù)端進(jìn)行通信,這個(gè)過程是很自然的。
那你真的了解過Service的綁定過程嗎?為什么可以是Binder和Service通信?
同樣的先看一張圖大致了解一下,灰色背景框起來的是同一個(gè)類的方法,如下:

我們知道調(diào)用Context的bindService方法即可綁定一個(gè)Service,而ContextImpl是Context的實(shí)現(xiàn)類。那接下來就從源碼的角度分析Service的綁定過程。
當(dāng)然是從ContextImpl的bindService方法開始,如下:
@Override
public boolean bindService(Intent service, ServiceConnection conn,
int flags) {
warnIfCallingFromSystemProcess();
return bindServiceCommon(service, conn, flags, mMainThread.getHandler(),
Process.myUserHandle());
}
在bindService方法中又會(huì)轉(zhuǎn)到bindServiceCommon方法,將Intent,ServiceConnection對(duì)象傳進(jìn)。
那就看看bindServiceCommon方法的實(shí)現(xiàn)。
private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags, Handler
handler, UserHandle user) {
IServiceConnection sd;
if (conn == null) {
throw new IllegalArgumentException("connection is null");
}
if (mPackageInfo != null) {
sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), handler, flags);
} else {
throw new RuntimeException("Not supported in system context");
}
validateServiceIntent(service);
try {
IBinder token = getActivityToken();
if (token == null && (flags&BIND_AUTO_CREATE) == 0 && mPackageInfo != null
&& mPackageInfo.getApplicationInfo().targetSdkVersion
< android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
flags |= BIND_WAIVE_PRIORITY;
}
service.prepareToLeaveProcess(this);
int res = ActivityManagerNative.getDefault().bindService(
mMainThread.getApplicationThread(), getActivityToken(), service,
service.resolveTypeIfNeeded(getContentResolver()),
sd, flags, getOpPackageName(), user.getIdentifier());
if (res < 0) {
throw new SecurityException(
"Not allowed to bind to service " + service);
}
return res != 0;
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
在上述代碼中,調(diào)用了mPackageInfo(LoadedApk對(duì)象)的getServiceDispatcher方法。從getServiceDispatcher方法的名字可以看出是獲取一個(gè)“服務(wù)分發(fā)者”。其實(shí)是根據(jù)這個(gè)“服務(wù)分發(fā)者”獲取到一個(gè)Binder對(duì)象的。
那現(xiàn)在就看到getServiceDispatcher方法的實(shí)現(xiàn)。
public final IServiceConnection getServiceDispatcher(ServiceConnection c,
Context context, Handler handler, int flags) {
synchronized (mServices) {
LoadedApk.ServiceDispatcher sd = null;
ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher> map = mServices.get(context);
if (map != null) {
sd = map.get(c);
}
if (sd == null) {
sd = new ServiceDispatcher(c, context, handler, flags);
if (map == null) {
map = new ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher>();
mServices.put(context, map);
}
map.put(c, sd);
} else {
sd.validate(context, handler);
}
return sd.getIServiceConnection();
}
}
從getServiceDispatcher方法的實(shí)現(xiàn)可以知道,ServiceConnection和ServiceDispatcher構(gòu)成了映射關(guān)系。當(dāng)存儲(chǔ)集合不為空的時(shí)候,根據(jù)傳進(jìn)的key,也就是ServiceConnection,來取出對(duì)應(yīng)的ServiceDispatcher對(duì)象。
當(dāng)取出ServiceDispatcher對(duì)象后,最后一行代碼是關(guān)鍵,
return sd.getIServiceConnection();
調(diào)用了ServiceDispatcher對(duì)象的getIServiceConnection方法。這個(gè)方法肯定是獲取一個(gè)IServiceConnection的。
IServiceConnection getIServiceConnection() {
return mIServiceConnection;
}
那么mIServiceConnection是什么?現(xiàn)在就可以來看下ServiceDispatcher類了。ServiceDispatcher是LoadedApk的內(nèi)部類,里面封裝了InnerConnection和ServiceConnection。如下:
static final class ServiceDispatcher {
private final ServiceDispatcher.InnerConnection mIServiceConnection;
private final ServiceConnection mConnection;
private final Context mContext;
private final Handler mActivityThread;
private final ServiceConnectionLeaked mLocation;
private final int mFlags;
private RuntimeException mUnbindLocation;
private boolean mForgotten;
private static class ConnectionInfo {
IBinder binder;
IBinder.DeathRecipient deathMonitor;
}
private static class InnerConnection extends IServiceConnection.Stub {
final WeakReference<LoadedApk.ServiceDispatcher> mDispatcher;
InnerConnection(LoadedApk.ServiceDispatcher sd) {
mDispatcher = new WeakReference<LoadedApk.ServiceDispatcher>(sd);
}
public void connected(ComponentName name, IBinder service) throws RemoteException {
LoadedApk.ServiceDispatcher sd = mDispatcher.get();
if (sd != null) {
sd.connected(name, service);
}
}
}
private final ArrayMap<ComponentName, ServiceDispatcher.ConnectionInfo> mActiveConnections
= new ArrayMap<ComponentName, ServiceDispatcher.ConnectionInfo>();
ServiceDispatcher(ServiceConnection conn,
Context context, Handler activityThread, int flags) {
mIServiceConnection = new InnerConnection(this);
mConnection = conn;
mContext = context;
mActivityThread = activityThread;
mLocation = new ServiceConnectionLeaked(null);
mLocation.fillInStackTrace();
mFlags = flags;
}
//代碼省略
}
先看到ServiceDispatcher的構(gòu)造方法,一個(gè)ServiceDispatcher關(guān)聯(lián)一個(gè)InnerConnection對(duì)象。而InnerConnection呢?,它是一個(gè)Binder,有一個(gè)很重要的connected方法。至于為什么要用Binder,因?yàn)榕cService通信可能是跨進(jìn)程的。
好,到了這里先總結(jié)一下:調(diào)用bindService方法綁定服務(wù),會(huì)轉(zhuǎn)到bindServiceCommon方法。
在bindServiceCommon方法中,會(huì)調(diào)用LoadedApk的getServiceDispatcher方法,并將ServiceConnection傳進(jìn), 根據(jù)這個(gè)ServiceConnection取出與其映射的ServiceDispatcher對(duì)象,最后調(diào)用這個(gè)ServiceDispatcher對(duì)象的getIServiceConnection方法獲取與其關(guān)聯(lián)的InnerConnection對(duì)象并返回。簡單點(diǎn)理解就是用ServiceConnection換來了InnerConnection。
現(xiàn)在回到bindServiceCommon方法,可以看到綁定Service的過程會(huì)轉(zhuǎn)到ActivityManagerNative.getDefault()的bindService方法,其實(shí)從拋出的異常類型RemoteException也可以知道與Service通信可能是跨進(jìn)程的,這個(gè)是很好理解的。
而ActivityManagerNative.getDefault()是ActivityManagerService,那么繼續(xù)跟進(jìn)ActivityManagerService的bindService方法即可,如下:
public int bindService(IApplicationThread caller, IBinder token, Intent service,
String resolvedType, IServiceConnection connection, int flags, String callingPackage,
int userId) throws TransactionTooLargeException {
enforceNotIsolatedCaller("bindService");
// Refuse possible leaked file descriptors
if (service != null && service.hasFileDescriptors() == true) {
throw new IllegalArgumentException("File descriptors passed in Intent");
}
if (callingPackage == null) {
throw new IllegalArgumentException("callingPackage cannot be null");
}
synchronized(this) {
return mServices.bindServiceLocked(caller, token, service,
resolvedType, connection, flags, callingPackage, userId);
}
}
在上述代碼中,綁定Service的過程轉(zhuǎn)到ActiveServices的bindServiceLocked方法,那就跟進(jìn)ActiveServices的bindServiceLocked方法瞧瞧。如下:
int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,
String resolvedType, final IServiceConnection connection, int flags,
String callingPackage, final int userId) throws TransactionTooLargeException {
//代碼省略
ConnectionRecord c = new ConnectionRecord(b, activity,
connection, flags, clientLabel, clientIntent);
IBinder binder = connection.asBinder();
ArrayList<ConnectionRecord> clist = s.connections.get(binder);
if (clist == null) {
clist = new ArrayList<ConnectionRecord>();
s.connections.put(binder, clist);
}
clist.add(c);
//代碼省略
if ((flags&Context.BIND_AUTO_CREATE) != 0) {
s.lastActivity = SystemClock.uptimeMillis();
if (bringUpServiceLocked(s, service.getFlags(), callerFg, false,
permissionsReviewRequired) != null) {
return 0;
}
}
//代碼省略
return 1;
}
將connection對(duì)象封裝在ConnectionRecord中,這里的connection就是上面提到的InnerConnection對(duì)象。這一步很重要的。
然后調(diào)用了bringUpServiceLocked方法,那么就探探這個(gè)bringUpServiceLocked方法,
private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
boolean whileRestarting, boolean permissionsReviewRequired)
throws TransactionTooLargeException {
//代碼省略
if (app != null && app.thread != null) {
try {
app.addPackage(r.appInfo.packageName, r.appInfo.versionCode, mAm.mProcessStats);
realStartServiceLocked(r, app, execInFg);
return null;
} catch (TransactionTooLargeException e) {
throw e;
} catch (RemoteException e) {
Slog.w(TAG, "Exception when starting service " + r.shortName, e);
}
// If a dead object exception was thrown -- fall through to
// restart the application.
}
//代碼省略
return null;
}
可以看到調(diào)用了realStartServiceLocked方法,真正去啟動(dòng)Service了。
那么跟進(jìn)realStartServiceLocked方法探探,如下:
private final void realStartServiceLocked(ServiceRecord r,
ProcessRecord app, boolean execInFg) throws RemoteException {
//代碼省略
app.thread.scheduleCreateService(r, r.serviceInfo,
mAm.compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo),
app.repProcState);
r.postNotification();
created = true;
//代碼省略
requestServiceBindingsLocked(r, execInFg);
updateServiceClientActivitiesLocked(app, null, true);
// If the service is in the started state, and there are no
// pending arguments, then fake up one so its onStartCommand() will
// be called.
if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
null, null));
}
sendServiceArgsLocked(r, execInFg, true);
//代碼省略
}
這里會(huì)調(diào)用app.thread的scheduleCreateService方法去創(chuàng)建一個(gè)Service,然后會(huì)回調(diào)Service的生命周期方法,然而綁定Service呢?
在上述代碼中,找到一個(gè)requestServiceBindingsLocked方法,從名字看是請(qǐng)求綁定服務(wù)的意思,那么就是它沒錯(cuò)了。
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);
if (!requestServiceBindingLocked(r, ibr, execInFg, false)) {
break;
}
}
}
咦,我再按住Ctrl+鼠標(biāo)左鍵,點(diǎn)進(jìn)去requestServiceBindingLocked方法。如下:
private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,
boolean execInFg, boolean rebind) throws TransactionTooLargeException {
if (r.app == null || r.app.thread == null) {
// If service is not currently running, can't yet bind.
return false;
}
if ((!i.requested || rebind) && i.apps.size() > 0) {
try {
bumpServiceExecutingLocked(r, execInFg, "bind");
r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,
r.app.repProcState);
if (!rebind) {
i.requested = true;
}
i.hasBound = true;
i.doRebind = false;
}
//代碼省略
return true;
}
r.app.thread調(diào)用了scheduleBindService方法來綁定服務(wù),而r.app.thread是ApplicationThread,現(xiàn)在關(guān)注到 ApplicationThread即可,scheduleBindService方法如下:
public final void scheduleBindService(IBinder token, Intent intent,
boolean rebind, int processState) {
updateProcessState(processState, false);
BindServiceData s = new BindServiceData();
s.token = token;
s.intent = intent;
s.rebind = rebind;
if (DEBUG_SERVICE)
Slog.v(TAG, "scheduleBindService token=" + token + " intent=" + intent + " uid="
+ Binder.getCallingUid() + " pid=" + Binder.getCallingPid());
sendMessage(H.BIND_SERVICE, s);
}
封裝了待綁定的Service的信息,并發(fā)送了一個(gè)消息給主線程,
public void handleMessage(Message msg) {
if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
switch (msg.what) {
//代碼省略
case BIND_SERVICE:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceBind");
handleBindService((BindServiceData)msg.obj);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
//代碼省略
}
}
調(diào)用了handleBindService方法,即將綁定完成啦。
private void handleBindService(BindServiceData data) {
Service s = mServices.get(data.token);
if (DEBUG_SERVICE)
Slog.v(TAG, "handleBindService s=" + s + " rebind=" + data.rebind);
if (s != null) {
try {
data.intent.setExtrasClassLoader(s.getClassLoader());
data.intent.prepareToEnterProcess();
try {
if (!data.rebind) {
IBinder binder = s.onBind(data.intent);
ActivityManagerNative.getDefault().publishService(
data.token, data.intent, binder);
} else {
s.onRebind(data.intent);
ActivityManagerNative.getDefault().serviceDoneExecuting(
data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
}
ensureJitEnabled();
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
} catch (Exception e) {
if (!mInstrumentation.onException(s, e)) {
throw new RuntimeException(
"Unable to bind to service " + s
+ " with " + data.intent + ": " + e.toString(), e);
}
}
}
}
根據(jù)token獲取到Service,然后Service回調(diào)onBind方法。結(jié)束了?
可是onBind方法返回了一個(gè)binder是用來干嘛的?
我們?cè)倏纯碅ctivityManagerNative.getDefault()調(diào)用了publishService方法做了什么工作,此時(shí)又回到了ActivityManagerService。
public void publishService(IBinder token, Intent intent, IBinder service) {
// Refuse possible leaked file descriptors
if (intent != null && intent.hasFileDescriptors() == true) {
throw new IllegalArgumentException("File descriptors passed in Intent");
}
synchronized(this) {
if (!(token instanceof ServiceRecord)) {
throw new IllegalArgumentException("Invalid service token");
}
mServices.publishServiceLocked((ServiceRecord)token, intent, service);
}
}
又會(huì)交給ActiveServices處理,轉(zhuǎn)到了publishServiceLocked方法,那看到ActiveServices的publishServiceLocked方法,
void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {
final long origId = Binder.clearCallingIdentity();
try {
if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "PUBLISHING " + r
+ " " + intent + ": " + service);
if (r != null) {
Intent.FilterComparison filter
= new Intent.FilterComparison(intent);
IntentBindRecord b = r.bindings.get(filter);
if (b != null && !b.received) {
b.binder = service;
b.requested = true;
b.received = true;
for (int conni=r.connections.size()-1; conni>=0; conni--) {
ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
for (int i=0; i<clist.size(); i++) {
ConnectionRecord c = clist.get(i);
if (!filter.equals(c.binding.intent.intent)) {
if (DEBUG_SERVICE) Slog.v(
TAG_SERVICE, "Not publishing to: " + c);
if (DEBUG_SERVICE) Slog.v(
TAG_SERVICE, "Bound intent: " + c.binding.intent.intent);
if (DEBUG_SERVICE) Slog.v(
TAG_SERVICE, "Published intent: " + intent);
continue;
}
if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Publishing to: " + c);
try {
c.conn.connected(r.name, service);
}
//代碼省略
}
c.conn是什么? 它是一個(gè)InnerConnection對(duì)象,對(duì),就是那個(gè)那個(gè)Binder,上面也貼出了代碼,在ActiveServices的bindServiceLocked方法中,InnerConnection對(duì)象被封裝在ConnectionRecord中。那么現(xiàn)在它調(diào)用了connected方法,就很好理解了。
InnerConnection的connected方法如下:
public void connected(ComponentName name, IBinder service) throws RemoteException {
LoadedApk.ServiceDispatcher sd = mDispatcher.get();
if (sd != null) {
sd.connected(name, service);
}
}
會(huì)調(diào)用ServiceDispatcher 的connected方法,如下
public void connected(ComponentName name, IBinder service) {
if (mActivityThread != null) {
mActivityThread.post(new RunConnection(name, service, 0));
} else {
doConnected(name, service);
}
}
從而ActivityThread會(huì)投遞一個(gè)消息到主線程,此時(shí)就解決了跨進(jìn)程通信。
那么你應(yīng)該猜到了RunConnection一定有在主線程回調(diào)的onServiceConnected方法,
private final class RunConnection implements Runnable {
RunConnection(ComponentName name, IBinder service, int command) {
mName = name;
mService = service;
mCommand = command;
}
public void run() {
if (mCommand == 0) {
doConnected(mName, mService);
} else if (mCommand == 1) {
doDeath(mName, mService);
}
}
final ComponentName mName;
final IBinder mService;
final int mCommand;
}
咦,還不出現(xiàn)?繼續(xù)跟進(jìn)doConnected方法,
public void doConnected(ComponentName name, IBinder service) {
ServiceDispatcher.ConnectionInfo old;
ServiceDispatcher.ConnectionInfo info;
synchronized (this) {
if (mForgotten) {
// We unbound before receiving the connection; ignore
// any connection received.
return;
}
old = mActiveConnections.get(name);
if (old != null && old.binder == service) {
// Huh, already have this one. Oh well!
return;
}
if (service != null) {
// A new service is being connected... set it all up.
info = new ConnectionInfo();
info.binder = service;
info.deathMonitor = new DeathMonitor(name, service);
try {
service.linkToDeath(info.deathMonitor, 0);
mActiveConnections.put(name, info);
} catch (RemoteException e) {
// This service was dead before we got it... just
// don't do anything with it.
mActiveConnections.remove(name);
return;
}
} else {
// The named service is being disconnected... clean up.
mActiveConnections.remove(name);
}
if (old != null) {
old.binder.unlinkToDeath(old.deathMonitor, 0);
}
}
// If there was an old service, it is not disconnected.
if (old != null) {
mConnection.onServiceDisconnected(name);
}
// If there is a new service, it is now connected.
if (service != null) {
mConnection.onServiceConnected(name, service);
}
}
在最后一個(gè)if判斷,終于找到了onServiceConnected方法!
總結(jié)一下,當(dāng)Service回調(diào)onBind方法,其實(shí)還沒有結(jié)束,會(huì)轉(zhuǎn)到ActivityManagerService,然后又會(huì)在ActiveServices的publishServiceLocked方法中,從ConnectionRecord中取出InnerConnection對(duì)象。有了InnerConnection對(duì)象后,就回調(diào)了它的connected。在InnerConnection的connected方法中,又會(huì)調(diào)用ServiceDispatcher的connected方法,在ServiceDispatcher的connected方法向主線程扔了一個(gè)消息,切換到了主線程,之后就在主線程中回調(diào)了客戶端傳進(jìn)的ServiceConnected對(duì)象的onServiceConnected方法。
至此, Service的綁定過程分析完畢。
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android添加自定義下拉刷新布局阻尼滑動(dòng)懸停彈動(dòng)畫效果
這篇文章主要為大家介紹了Android添加自定義下拉刷新布局阻尼滑動(dòng)懸停彈動(dòng)畫效果詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02
Android 優(yōu)化之存儲(chǔ)優(yōu)化的實(shí)現(xiàn)
這篇文章主要介紹了Android 優(yōu)化之存儲(chǔ)優(yōu)化的實(shí)現(xiàn),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-07-07
Android使用手勢(shì)實(shí)現(xiàn)翻頁效果
這篇文章主要介紹了Android使用手勢(shì)實(shí)現(xiàn)翻頁效果,本程序使用了一個(gè)ViewFlipper組件,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-09-09
使用User Agent分辨出Android設(shè)備類型的安全做法
這篇文章主要介紹了使用User Agent分辨出Android設(shè)備類型的安全做法,本文得出的結(jié)論是當(dāng)你依據(jù)檢測(cè)UA來判斷Android手機(jī)設(shè)備,請(qǐng)同時(shí)檢查android和mobile兩個(gè)字符串,需要的朋友可以參考下2015-01-01
Android仿天貓橫向滑動(dòng)指示器功能的實(shí)現(xiàn)
這篇文章主要介紹了Android仿天貓橫向滑動(dòng)指示器,Android開發(fā)中會(huì)有很多很新奇的交互,比如天貓商城的首頁頭部的分類,使用的是GridLayoutManager+橫向指示器實(shí)現(xiàn)的,需要的朋友可以參考下2022-08-08
Android判斷網(wǎng)絡(luò)類型的方法(2g,3g還是wifi)
這篇文章主要介紹了Android判斷網(wǎng)絡(luò)類型的方法,可實(shí)現(xiàn)判斷2g,3g還是wifi的功能,結(jié)合實(shí)例形式分析了Android針對(duì)網(wǎng)絡(luò)類型的相關(guān)判定技巧,需要的朋友可以參考下2016-02-02
android自定義toast(widget開發(fā))示例
這篇文章主要介紹了android自定義toast(widget開發(fā))示例,需要的朋友可以參考下2014-03-03

