一、引言
Service是Android中的四大組件之一,在開發(fā)中也是經(jīng)常使用的。Service的用法比較簡單,本文不對此進行討論。但是,我們用了這么久的Service,是否有想過以下問題:
1、Service的幾個生命周期方法是運行在哪個線程的?是主線程還是子線程?
2、當(dāng)使用bindService后,ServiceConnection的回調(diào)方法onServiceConnected和onServiceDisconnected方法又是運行在哪個線程的?是主線程還是子線程?
針對上面的兩個問題,本文從Android源碼的角度進行解析,并給出答案。好了,下面讓我們開始進入源碼的世界吧!
二、Service的生命周期方法執(zhí)行時所處的線程
Service的生命周期方法是onCreate、onStartCommand、onDestroy、onBind、onUnBind。
2.1、onCreate方法
首先看onCreate方法。從之前的文章【源碼解析】Service的工作過程 分析知道,Service的onCreate方法是在ActivityThread的handleCreateService方法調(diào)用的,如下所示:
private void handleCreateService(CreateServiceData data) {
...省略
LoadedApk packageInfo = getPackageInfoNoCheck(
data.info.applicationInfo, data.compatInfo);
Service service = null;
try {
java.lang.ClassLoader cl = packageInfo.getClassLoader();
service = (Service) cl.loadClass(data.info.name).newInstance();
} catch (Exception e) {
...省略
}
try {
ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
context.setOuterContext(service);
Application app = packageInfo.makeApplication(false, mInstrumentation);
service.attach(context, this, data.info.name, data.token, app,
ActivityManager.getService());
service.onCreate(); //Service的onCreate方法被調(diào)用
mServices.put(data.token, service);
try {
ActivityManager.getService().serviceDoneExecuting(
data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
} catch (Exception e) {
...省略
}
}
所以要確定onCreate方法的運行線程,就要確定handleCreateService方法的運行線程,可以看到handleCreateService方法是私有方法,它在H類的handleMessage方法中被調(diào)用,如下所示:
public void handleMessage(Message msg) {
switch (msg.what) {
...省略
case CREATE_SERVICE:
handleCreateService((CreateServiceData)msg.obj);
break;
...省略
}
}
所以要確定handleCreateService方法的運行線程,就有確定handleMessage方法的運行線程。由于handleMessage是H類的方法,H類是一個Handler類,所以handleMessage方法的運行線程由創(chuàng)建H類時的Looper對象決定。所以,我們轉(zhuǎn)而找到H類創(chuàng)建的代碼,如下所示:
final H mH = new H();
H類創(chuàng)建時并沒有傳入相關(guān)的Looper對象,所以默認的使用了其創(chuàng)建時的當(dāng)前線程,而mH是ActivityThread的一個成員變量,所以其創(chuàng)建時的當(dāng)前線程就是ActivityThread對象生成時的當(dāng)前線程。
那么ActivityThread對象是什么時候生成的呢?ActivityThread對象是在ActivityThread的main函數(shù)中生成的,如下所示:
public static void main(String[] args) {
...省略
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
我們知道m(xù)ain函數(shù)是一個應(yīng)用的真正入口,它是在主進程中的主線程執(zhí)行的,并且之后執(zhí)行一次,所以說明了ActivityThread對象創(chuàng)建時所處的線程是主線程。這樣,我們就可以回溯證明ActivityThread的mH對象消息處理的運行線程也是主線程,最后倒推證明onCreate方法是在主線程中運行的。
2.2、其他生命周期方法
由于其他生命周期方法同樣是在ActivityThread中通過mH發(fā)送消息,并由handleMessage處理的,所以它們和onCreate方法一樣,也是運行在主線程。這里就不再重復(fù)分析,大家可以自己驗證一下。
三、ServiceConnection的回調(diào)方法所處的線程
上面的結(jié)論告訴我們,Service的生命周期方法onBind是運行在主線程的,而onBind方法是在handleBindService方法中執(zhí)行的,我們接著分析ServiceConnection的回調(diào)方法所處的線程。
3.1、onServiceConnected方法
由之前的文章【源碼解析】Service的工作過程 分析知道,ServiceConnection的回調(diào)方法onServiceConnected是在onBind方法后執(zhí)行的,如下所示:
private void handleBindService(BindServiceData data) {
Service s = mServices.get(data.token);
if (s != null) {
try {
data.intent.setExtrasClassLoader(s.getClassLoader());
data.intent.prepareToEnterProcess();
try {
if (!data.rebind) {
IBinder binder = s.onBind(data.intent);
ActivityManager.getService().publishService(
data.token, data.intent, binder);
} else {
s.onRebind(data.intent);
ActivityManager.getService().serviceDoneExecuting(
data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
}
ensureJitEnabled();
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
} catch (Exception e) {
...省略
}
}
}
可以看到,在執(zhí)行了onBind方法后,得到了該Service對象的一個句柄binder,緊接著調(diào)用了ActivityManager.getService()的publishService方法,ActivityManager.getService()是一個ActivityManagerService對象,它的publishService方法如下所示:
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);
}
}
由于ActivityManagerService對象是在系統(tǒng)進程中,所以當(dāng)前線程會掛起,并調(diào)用系統(tǒng)進程中的ActivityManagerService對象的publishService方法,而publishService方法又調(diào)用了publishServiceLocked方法,如下所示:
void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {
final long origId = Binder.clearCallingIdentity();
try {
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)) {
continue;
}
try {
//這里又從系統(tǒng)進程回到了應(yīng)用進程
c.conn.connected(r.name, service, false);
} catch (Exception e) {
...省略
}
}
}
}
serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false);
}
} finally {
Binder.restoreCallingIdentity(origId);
}
}
由之前的文章【源碼解析】Service的工作過程 分析知道,c.conn.connected又從系統(tǒng)的服務(wù)進程回到了應(yīng)用進程,并且該connected方法就是LoadApk的內(nèi)部類InnerConnection的connected方法,如下所示:
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, boolean dead)
throws RemoteException {
LoadedApk.ServiceDispatcher sd = mDispatcher.get();
if (sd != null) {
sd.connected(name, service, dead);
}
}
}
這里繼而調(diào)用了LoadedApk的ServiceDispatcher對象的connected方法,如下所示:
public void connected(ComponentName name, IBinder service, boolean dead) {
if (mActivityThread != null) {
mActivityThread.post(new RunConnection(name, service, 0, dead));
} else {
doConnected(name, service, dead);
}
}
而上面不管是調(diào)用mActivityThread對象的post方法,或者是直接調(diào)用doConnected方法,最終都會調(diào)用到doConnected方法,而這兩個方法調(diào)用的doConnected方法都運行在主線程中,我們再來看doConnected方法,如下所示:
public void doConnected(ComponentName name, IBinder service, boolean dead) {
ServiceDispatcher.ConnectionInfo old;
ServiceDispatcher.ConnectionInfo info;
...省略
// If there was an old service, it is now disconnected.
if (old != null) {
mConnection.onServiceDisconnected(name);
}
if (dead) {
mConnection.onBindingDied(name);
}
// If there is a new service, it is now connected.
if (service != null) {
mConnection.onServiceConnected(name, service);
}
}
可以清晰的看到doConnected方法調(diào)用了ServiceConnection對象的onServiceConnected方法,這就是證明了onServiceConnected方法是運行在主線程的。
3.2、onServiceDisconnected方法
在doConnected方法中也同時看到了onServiceDisconnected方法會被調(diào)用,所以同時也證明了onServiceDisconnected方法是運行在主線程的。
四、總結(jié)
從源碼中分析得到以下結(jié)論:Service的所有生命周期方法和ServiceConnection的回調(diào)方法都是運行在主線程的。所以在開發(fā)中特別要注意,千萬不能在Service的生命周期方法中做非常耗時的操作,否則會引起主線程卡頓,嚴重時還會引起ANR。