- ActivityManagerService中的startProcessLocked()方法
創(chuàng)建新進(jìn)程的消息進(jìn)入到AMS的startProcessLocked()中,然后直接傳入到ProcessList中的startProcessLocked()方法中
- 首先調(diào)用ProcessList的startProcessLocked方法來(lái)啟動(dòng)進(jìn)程,需要傳入進(jìn)程名谊迄、應(yīng)用程序信息赵刑、是否已知進(jìn)程已經(jīng)死亡蜈项、意圖標(biāo)志、宿主記錄办桨、Zygote策略標(biāo)志搭综、是否允許在系統(tǒng)啟動(dòng)時(shí)啟動(dòng)進(jìn)程垢箕、是否隔離進(jìn)程、是否保留大進(jìn)程等參數(shù)兑巾;
- 然后返回一個(gè)ProcessRecord對(duì)象条获,這個(gè)對(duì)象代表了新啟動(dòng)的進(jìn)程。
final ProcessRecord startProcessLocked(String processName,
ApplicationInfo info, boolean knownToBeDead, int intentFlags,
HostingRecord hostingRecord, int zygotePolicyFlags, boolean allowWhileBooting,
boolean isolated, boolean keepIfLarge) {
return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags,
hostingRecord, zygotePolicyFlags, allowWhileBooting, isolated, 0 /* isolatedUid */,
keepIfLarge, null /* ABI override */, null /* entryPoint */,
null /* entryPointArgs */, null /* crashHandler */);
}
- ProcessList中的startProcessLocked()方法
ProcessList內(nèi)部會(huì)創(chuàng)建一個(gè)AppZygote對(duì)象蒋歌,然后孵化出新的進(jìn)程帅掘;
該方法接收14個(gè)創(chuàng)建進(jìn)程的參數(shù),包括進(jìn)程名堂油、應(yīng)用程序信息修档、是否已知為死亡狀態(tài)、意圖標(biāo)志府框、宿主記錄吱窝、Zygote策略標(biāo)志、是否允許在系統(tǒng)啟動(dòng)時(shí)運(yùn)行、是否隔離院峡、隔離UID兴使、是否保持大進(jìn)程、ABI覆蓋照激、入口點(diǎn)发魄、入口點(diǎn)參數(shù)和崩潰處理程序。
首先檢查是否需要?jiǎng)?chuàng)建新的進(jìn)程俩垃。如果不需要?jiǎng)?chuàng)建新進(jìn)程励幼,它會(huì)檢查進(jìn)程是否已經(jīng)存在并且處于活動(dòng)狀態(tài)。如果進(jìn)程已經(jīng)存在并且處于活動(dòng)狀態(tài)口柳,它會(huì)將應(yīng)用程序信息添加到進(jìn)程中并返回該進(jìn)程苹粟。如果進(jìn)程已經(jīng)存在但處于非活動(dòng)狀態(tài),它會(huì)殺死該進(jìn)程并創(chuàng)建一個(gè)新的進(jìn)程記錄啄清。
如果需要?jiǎng)?chuàng)建新進(jìn)程六水,它會(huì)創(chuàng)建一個(gè)新的進(jìn)程記錄俺孙,并將應(yīng)用程序信息添加到該進(jìn)程中辣卒。然后,它會(huì)檢查系統(tǒng)是否準(zhǔn)備好運(yùn)行新進(jìn)程睛榄。如果系統(tǒng)尚未準(zhǔn)備好運(yùn)行新進(jìn)程荣茫,它會(huì)將進(jìn)程置于等待狀態(tài)。最后场靴,它會(huì)調(diào)用startProcessLocked()方法來(lái)啟動(dòng)新進(jìn)程啡莉,并根據(jù)啟動(dòng)結(jié)果返回相應(yīng)的進(jìn)程記錄或null。
final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
boolean knownToBeDead, int intentFlags, HostingRecord hostingRecord,
int zygotePolicyFlags, boolean allowWhileBooting, boolean isolated, int isolatedUid,
boolean keepIfLarge, String abiOverride, String entryPoint, String[] entryPointArgs,
Runnable crashHandler) {
long startTime = SystemClock.uptimeMillis();
ProcessRecord app;
if (!isolated) {
app = getProcessRecordLocked(processName, info.uid, keepIfLarge);
checkSlow(startTime, "startProcess: after getProcessRecord");
if ((intentFlags & Intent.FLAG_FROM_BACKGROUND) != 0) {
if (mService.mAppErrors.isBadProcessLocked(info)) {
if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
+ "/" + info.processName);
return null;
}
} else {
if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
+ "/" + info.processName);
mService.mAppErrors.resetProcessCrashTimeLocked(info);
if (mService.mAppErrors.isBadProcessLocked(info)) {
EventLog.writeEvent(EventLogTags.AM_PROC_GOOD,
UserHandle.getUserId(info.uid), info.uid,
info.processName);
mService.mAppErrors.clearBadProcessLocked(info);
if (app != null) {
app.bad = false;
}
}
}
} else {
app = null;
}
if (DEBUG_PROCESSES) Slog.v(TAG_PROCESSES, "startProcess: name=" + processName
+ " app=" + app + " knownToBeDead=" + knownToBeDead
+ " thread=" + (app != null ? app.thread : null)
+ " pid=" + (app != null ? app.pid : -1));
ProcessRecord precedence = null;
if (app != null && app.pid > 0) {
if ((!knownToBeDead && !app.killed) || app.thread == null) {
if (DEBUG_PROCESSES) Slog.v(TAG_PROCESSES, "App already running: " + app);
app.addPackage(info.packageName, info.longVersionCode, mService.mProcessStats);
checkSlow(startTime, "startProcess: done, added package to proc");
return app;
}
if (DEBUG_PROCESSES) Slog.v(TAG_PROCESSES, "App died: " + app);
checkSlow(startTime, "startProcess: bad proc running, killing");
ProcessList.killProcessGroup(app.uid, app.pid);
checkSlow(startTime, "startProcess: done killing old proc");
Slog.wtf(TAG_PROCESSES, app.toString() + " is attached to a previous process");
precedence = app;
app = null;
}
if (app == null) {
checkSlow(startTime, "startProcess: creating new process record");
app = newProcessRecordLocked(info, processName, isolated, isolatedUid, hostingRecord);
if (app == null) {
Slog.w(TAG, "Failed making new process record for "
+ processName + "/" + info.uid + " isolated=" + isolated);
return null;
}
app.crashHandler = crashHandler;
app.isolatedEntryPoint = entryPoint;
app.isolatedEntryPointArgs = entryPointArgs;
if (precedence != null) {
app.mPrecedence = precedence;
precedence.mSuccessor = app;
}
checkSlow(startTime, "startProcess: done creating new process record");
} else {
app.addPackage(info.packageName, info.longVersionCode, mService.mProcessStats);
checkSlow(startTime, "startProcess: added package to existing proc");
}
if (!mService.mProcessesReady
&& !mService.isAllowedWhileBooting(info)
&& !allowWhileBooting) {
if (!mService.mProcessesOnHold.contains(app)) {
mService.mProcessesOnHold.add(app);
}
if (DEBUG_PROCESSES) Slog.v(TAG_PROCESSES,
"System not ready, putting on hold: " + app);
checkSlow(startTime, "startProcess: returning with proc on hold");
return app;
}
checkSlow(startTime, "startProcess: stepping in to startProcess");
final boolean success =
startProcessLocked(app, hostingRecord, zygotePolicyFlags, abiOverride);
checkSlow(startTime, "startProcess: done starting proc!");
return success ? app : null;
}
- ProcessList中的startProcessLocked()方法
啟動(dòng)新進(jìn)程的過(guò)程:
- 上面一個(gè)ProcessList中的startProcessLocked()方法接收了14個(gè)參數(shù)旨剥,進(jìn)行了一些操作之后調(diào)用startProcessLocked()方法傳遞了4個(gè)參數(shù)進(jìn)去來(lái)啟動(dòng)新進(jìn)程咧欣;
- 接收4個(gè)參數(shù)的startProcessLocked()方法直接 return startProcessLocked()方法,增加了一些參數(shù)默認(rèn)值轨帜,跳轉(zhuǎn)到了接收7個(gè)參數(shù)的startProcessLocked()方法魄咕;
- 接收7個(gè)參數(shù)的startProcessLocked()方法又進(jìn)行了一些處理,最后還是返回一個(gè)startProcessLocked()方法蚌父,并傳入13個(gè)參數(shù)哮兰;
接收13個(gè)參數(shù)的startProcessLocked()方法:
- 首先設(shè)置進(jìn)程記錄的一些屬性,如禁用的兼容性更改苟弛、啟動(dòng)參數(shù)和使用包裝器喝滞,將進(jìn)程記錄添加到待處理啟動(dòng)列表中;
- 根據(jù)系統(tǒng)配置膏秫,可以異步啟動(dòng)進(jìn)程或同步啟動(dòng)進(jìn)程右遭,如果異步啟動(dòng)進(jìn)程,它會(huì)將進(jìn)程啟動(dòng)消息發(fā)布到處理程序中,并返回true窘哈;如果選擇同步啟動(dòng)進(jìn)程言蛇,它會(huì)嘗試startProcess啟動(dòng)進(jìn)程,并在成功時(shí)處理進(jìn)程啟動(dòng)結(jié)果宵距,否則會(huì)強(qiáng)制停止應(yīng)用程序并返回false腊尚;
boolean startProcessLocked(HostingRecord hostingRecord, String entryPoint, ProcessRecord app,
int uid, int[] gids, int runtimeFlags, int zygotePolicyFlags, int mountExternal,
String seInfo, String requiredAbi, String instructionSet, String invokeWith,
long startTime) {
app.pendingStart = true;
app.killedByAm = false;
app.removed = false;
app.killed = false;
if (app.startSeq != 0) {
Slog.wtf(TAG, "startProcessLocked processName:" + app.processName
+ " with non-zero startSeq:" + app.startSeq);
}
if (app.pid != 0) {
Slog.wtf(TAG, "startProcessLocked processName:" + app.processName
+ " with non-zero pid:" + app.pid);
}
app.mDisabledCompatChanges = null;
if (mPlatformCompat != null) {
app.mDisabledCompatChanges = mPlatformCompat.getDisabledChanges(app.info);
}
final long startSeq = app.startSeq = ++mProcStartSeqCounter;
app.setStartParams(uid, hostingRecord, seInfo, startTime);
app.setUsingWrapper(invokeWith != null
|| Zygote.getWrapProperty(app.processName) != null);
mPendingStarts.put(startSeq, app);
if (mService.mConstants.FLAG_PROCESS_START_ASYNC) {
if (DEBUG_PROCESSES) Slog.i(TAG_PROCESSES,
"Posting procStart msg for " + app.toShortString());
mService.mProcStartHandler.post(() -> handleProcessStart(
app, entryPoint, gids, runtimeFlags, zygotePolicyFlags, mountExternal,
requiredAbi, instructionSet, invokeWith, startSeq));
return true;
} else {
try {
final Process.ProcessStartResult startResult = startProcess(hostingRecord,
entryPoint, app,
uid, gids, runtimeFlags, zygotePolicyFlags, mountExternal, seInfo,
requiredAbi, instructionSet, invokeWith, startTime);
handleProcessStartedLocked(app, startResult.pid, startResult.usingWrapper,
startSeq, false);
} catch (RuntimeException e) {
Slog.e(ActivityManagerService.TAG, "Failure starting process "
+ app.processName, e);
app.pendingStart = false;
mService.forceStopPackageLocked(app.info.packageName, UserHandle.getAppId(app.uid),
false, false, true, false, false, app.userId, "start failure");
}
return app.pid > 0;
}
}
- ProcessList中的startProcess()方法
ProcessList中的startProcess()方法的作用是啟動(dòng)一個(gè)新的進(jìn)程;
- 檢查是否需要使用WebView Zygote或App Zygote來(lái)啟動(dòng)新進(jìn)程满哪。
- 如果需要婿斥,為新進(jìn)程創(chuàng)建一個(gè)App Zygote實(shí)例。
- 根據(jù)不同的條件哨鸭,調(diào)用Process類(lèi)的start方法來(lái)啟動(dòng)新進(jìn)程民宿。
- 返回一個(gè)ProcessStartResult對(duì)象,表示新進(jìn)程的啟動(dòng)結(jié)果像鸡。
private Process.ProcessStartResult startProcess(HostingRecord hostingRecord, String entryPoint,
ProcessRecord app, int uid, int[] gids, int runtimeFlags, int zygotePolicyFlags,
int mountExternal, String seInfo, String requiredAbi, String instructionSet,
String invokeWith, long startTime) {
try {
...
final Process.ProcessStartResult startResult;
if (hostingRecord.usesWebviewZygote()) {
startResult = startWebView(entryPoint,
app.processName, uid, uid, gids, runtimeFlags, mountExternal,
app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
app.info.dataDir, null, app.info.packageName, app.mDisabledCompatChanges,
new String[]{PROC_START_SEQ_IDENT + app.startSeq});
} else if (hostingRecord.usesAppZygote()) {
final AppZygote appZygote = createAppZygoteForProcessIfNeeded(app);
// We can't isolate app data and storage data as parent zygote already did that.
startResult = appZygote.getProcess().start(entryPoint,
app.processName, uid, uid, gids, runtimeFlags, mountExternal,
app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
app.info.dataDir, null, app.info.packageName,
/*zygotePolicyFlags=*/ ZYGOTE_POLICY_FLAG_EMPTY, isTopApp,
app.mDisabledCompatChanges, pkgDataInfoMap, whitelistedAppDataInfoMap,
false, false,
new String[]{PROC_START_SEQ_IDENT + app.startSeq});
} else {
...
}
}
}
從系統(tǒng)服務(wù)回到Activity線(xiàn)程中
- ActivityThread中的main()方法
ActivityThread的主函數(shù)main()是Android應(yīng)用程序的入口點(diǎn)活鹰,負(fù)責(zé)初始化和啟動(dòng)應(yīng)用程序,會(huì)處理創(chuàng)建Looper對(duì)象以啟動(dòng)消息循環(huán)只估、注冊(cè)ActivityManager回調(diào)等志群;
- 在應(yīng)用程序啟動(dòng)時(shí),系統(tǒng)會(huì)調(diào)用ActivityThread.main()方法創(chuàng)建一個(gè)ActivityThread實(shí)例蛔钙,并調(diào)用其attach()方法將該實(shí)例與當(dāng)前應(yīng)用程序關(guān)聯(lián)锌云;
- 調(diào)用ActivityManagerService的startActivity()方法來(lái)啟動(dòng)應(yīng)用程序的主Activity,并通過(guò)Instrumentation類(lèi)來(lái)調(diào)用Application對(duì)象的onCreate()方法和主Activity的onCreate()方法完成應(yīng)用進(jìn)程的啟動(dòng)吁脱;
- 開(kāi)始跟蹤ActivityManager的啟動(dòng)過(guò)程桑涎。
- 安裝選擇性系統(tǒng)調(diào)用攔截。
- 關(guān)閉CloseGuard兼贡,因?yàn)樗赡軙?huì)產(chǎn)生很多不必要的日志攻冷。
- 初始化當(dāng)前用戶(hù)的環(huán)境。
- 確保TrustedCertificateStore在正確的位置查找CA證書(shū)遍希。
- 調(diào)用每個(gè)進(jìn)程的主要模塊初始化等曼。
- 設(shè)置進(jìn)程參數(shù)。
- 準(zhǔn)備主線(xiàn)程的Looper孵班。
- 從命令行中查找PROC_START_SEQ_IDENT的值涉兽,如果提供了該值,它將以"seq=114"的格式出現(xiàn)篙程。
- 創(chuàng)建一個(gè)新的ActivityThread實(shí)例枷畏,并將其附加到主線(xiàn)程。
- 如果sMainThreadHandler為null虱饿,則將其設(shè)置為新創(chuàng)建的ActivityThread的Handler拥诡。
- 如果需要触趴,啟用消息日志記錄。
- 結(jié)束跟蹤ActivityManager的啟動(dòng)過(guò)程渴肉。
- 進(jìn)入主線(xiàn)程的Looper循環(huán)冗懦。
- 如果主線(xiàn)程循環(huán)意外退出,則拋出一個(gè)運(yùn)行時(shí)異常仇祭。
其中主要步驟是:
- Looper.prepareMainLooper()初始化looper披蕉;
- new ActivityThread()創(chuàng)建一個(gè)新的ActivityThread實(shí)例,thread.attach將其附加到主線(xiàn)程上乌奇。
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
// Install selective syscall interception
AndroidOs.install();
// CloseGuard defaults to true and can be quite spammy. We
// disable it here, but selectively enable it later (via
// StrictMode) on debug builds, but using DropBox, not logs.
CloseGuard.setEnabled(false);
Environment.initForCurrentUser();
// Make sure TrustedCertificateStore looks in the right place for CA certificates
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
// Call per-process mainline module initialization.
initializeMainlineModules();
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper();
// Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
// It will be in the format "seq=114"
long startSeq = 0;
if (args != null) {
for (int i = args.length - 1; i >= 0; --i) {
if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
startSeq = Long.parseLong(
args[i].substring(PROC_START_SEQ_IDENT.length()));
}
}
}
ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
- ActivityThread中的attach()方法
ActivityThread的attach()方法主要負(fù)責(zé)向系統(tǒng)服務(wù)AMS注冊(cè)目標(biāo)Activity對(duì)應(yīng)的進(jìn)程益楼,并傳遞IApplicationThreadBinder對(duì)象以便于系統(tǒng)能夠?qū)Ρ具M(jìn)程進(jìn)行調(diào)度和管理他嚷;
- 設(shè)置當(dāng)前ActivityThread為系統(tǒng)線(xiàn)程或者應(yīng)用程序線(xiàn)程(ActivityThread.main()方法傳參設(shè)置當(dāng)前ActivityThread非系統(tǒng)線(xiàn)程);
- 如果當(dāng)前線(xiàn)程不是系統(tǒng)線(xiàn)程刊橘,那么會(huì)調(diào)用ActivityManager的attachApplication()方法將應(yīng)用程序綁定到AMS闰挡;
- 如果當(dāng)前線(xiàn)程是系統(tǒng)線(xiàn)程帅涂,那么會(huì)創(chuàng)建一個(gè)Instrumentation對(duì)象姚淆,并初始化它勤哗,然后創(chuàng)建一個(gè)應(yīng)用程序上下文,并實(shí)例化一個(gè)應(yīng)用程序?qū)ο笫柽叮詈笳{(diào)用應(yīng)用程序?qū)ο蟮膐nCreate方法潘靖;
- 注冊(cè)一個(gè)配置改變的回調(diào)函數(shù),當(dāng)配置發(fā)生改變時(shí)考廉,會(huì)通知所有的視圖層次結(jié)構(gòu)秘豹;
- 添加一個(gè)垃圾回收監(jiān)視器,當(dāng)Dalvik虛擬機(jī)使用的內(nèi)存超過(guò)其最大內(nèi)存的75%時(shí)昌粤,會(huì)嘗試釋放一些活動(dòng)來(lái)節(jié)省內(nèi)存;
- attachApplication()傳入的mAppThread類(lèi)型是ApplicationThread啄刹,是IApplicationThread的Binder接口本地實(shí)現(xiàn)類(lèi)涮坐,用來(lái)接收AMS等其他進(jìn)程的信息;
- mgr.attachApplication(mAppThread, startSeq)是一次IPC過(guò)程誓军,會(huì)調(diào)用AMS服務(wù)中對(duì)應(yīng)的方法袱讹;
private void attach(boolean system, long startSeq) {
...
if (!system) {
...
final IActivityManager mgr = ActivityManager.getService();
try {
mgr.attachApplication(mAppThread, startSeq);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
...
}else{
try {
mInstrumentation = new Instrumentation();
mInstrumentation.basicInit(this);
ContextImpl context = ContextImpl.createAppContext(
this, getSystemContext().mPackageInfo);
mInitialApplication = context.mPackageInfo.makeApplication(true, null);
mInitialApplication.onCreate();
} catch (Exception e) {
throw new RuntimeException(
"Unable to instantiate Application():" + e.toString(), e);
}
}
...
- ActivityManagerService中的attachApplication()方法
attachApplication()方法作用是為應(yīng)用創(chuàng)建必要的環(huán)境,如創(chuàng)建進(jìn)程狀態(tài)記錄昵时、分配進(jìn)程ID等捷雕,并將應(yīng)用程序綁定到AMS;
- 檢查傳入的IApplicationThread對(duì)象是否為null壹甥,如果為null則拋出SecurityException異常救巷;
- 獲取調(diào)用進(jìn)程的PID和UID;
- 清除調(diào)用進(jìn)程的身份標(biāo)識(shí)句柠,以便在后續(xù)操作中不受調(diào)用進(jìn)程的影響浦译;
- 調(diào)用attachApplicationLocked方法棒假,將應(yīng)用程序綁定到AMS;
- 恢復(fù)調(diào)用進(jìn)程的身份標(biāo)識(shí)精盅;
public final void attachApplication(IApplicationThread thread, long startSeq) {
if (thread == null) {
throw new SecurityException("Invalid application interface");
}
synchronized (this) {
int callingPid = Binder.getCallingPid();
final int callingUid = Binder.getCallingUid();
final long origId = Binder.clearCallingIdentity();
attachApplicationLocked(thread, callingPid, callingUid, startSeq);
Binder.restoreCallingIdentity(origId);
}
}
- ActivityManagerService中的attachApplicationLocked()方法
通過(guò)attachApplicationLocked()方法負(fù)責(zé)創(chuàng)建和管理應(yīng)用的全局狀態(tài)帽哑,還確保了應(yīng)用進(jìn)程與系統(tǒng)服務(wù)之間的正確通信,AMS能夠?yàn)樾聠?dòng)的應(yīng)用進(jìn)程創(chuàng)建必要的記錄和環(huán)境叹俏,從而能夠?qū)?yīng)用進(jìn)行有效的管理和調(diào)度妻枕。
- 注冊(cè)進(jìn)程死亡回調(diào):attachApplicationLocked()方法內(nèi)部注冊(cè)新創(chuàng)建的進(jìn)程的死亡回調(diào),創(chuàng)建一個(gè)AppDeathRecipient對(duì)象并將其與ActivityThread的Binder對(duì)象關(guān)聯(lián)粘驰,這樣做可以確保當(dāng)應(yīng)用程序的進(jìn)程意外終止時(shí)佳头,AMS能夠及時(shí)得知并做出相應(yīng)處理;
- 啟動(dòng)Application:調(diào)用ActivityThread的bindApplication()方法來(lái)啟動(dòng)應(yīng)用程序的Application對(duì)象晴氨,Application對(duì)象代表了應(yīng)用程序的全局狀態(tài)康嘉,并且是很多應(yīng)用級(jí)操作的起點(diǎn);
private boolean attachApplicationLocked(@NonNull IApplicationThread thread,
int pid, int callingUid, long startSeq) {
ProcessRecord app;
...
if (app.isolatedEntryPoint != null) {
// This is an isolated process which should just call an entry point instead of
// being bound to an application.
thread.runIsolatedEntryPoint(app.isolatedEntryPoint, app.isolatedEntryPointArgs);
} else if (instr2 != null) {
thread.bindApplication(processName, appInfo, providerList,
instr2.mClass,
profilerInfo, instr2.mArguments,
instr2.mWatcher,
instr2.mUiAutomationConnection, testMode,
mBinderTransactionTrackingEnabled, enableTrackAllocation,
isRestrictedBackupMode || !normalMode, app.isPersistent(),
new Configuration(app.getWindowProcessController().getConfiguration()),
app.compat, getCommonServicesLocked(app.isolated),
mCoreSettingsObserver.getCoreSettingsLocked(),
buildSerial, autofillOptions, contentCaptureOptions,
app.mDisabledCompatChanges);
} else {
thread.bindApplication(processName, appInfo, providerList, null, profilerInfo,
null, null, null, testMode,
mBinderTransactionTrackingEnabled, enableTrackAllocation,
isRestrictedBackupMode || !normalMode, app.isPersistent(),
new Configuration(app.getWindowProcessController().getConfiguration()),
app.compat, getCommonServicesLocked(app.isolated),
mCoreSettingsObserver.getCoreSettingsLocked(),
buildSerial, autofillOptions, contentCaptureOptions,
app.mDisabledCompatChanges);
}
...
- ActivityThread的bindApplication()方法
ActivityThread的bindApplication()方法負(fù)責(zé)將應(yīng)用程序的 Application 對(duì)象與操作系統(tǒng)進(jìn)行綁定籽前,并完成一系列的初始化工作亭珍;
- bindApplication接收到來(lái)自AMS的綁定信息,主要是processName和ApplicationInfo枝哄;
- 最后給主線(xiàn)程Handler H 發(fā)送送一條信息肄梨,進(jìn)程接收到的信息交由H處理;
public final void bindApplication(String processName, ApplicationInfo appInfo,
ProviderInfoList providerList, ComponentName instrumentationName,
ProfilerInfo profilerInfo, Bundle instrumentationArgs,
IInstrumentationWatcher instrumentationWatcher,
IUiAutomationConnection instrumentationUiConnection, int debugMode,
boolean enableBinderTracking, boolean trackAllocation,
boolean isRestrictedBackupMode, boolean persistent, Configuration config,
CompatibilityInfo compatInfo, Map services, Bundle coreSettings,
String buildSerial, AutofillOptions autofillOptions,
ContentCaptureOptions contentCaptureOptions, long[] disabledCompatChanges) {
...
setCoreSettings(coreSettings);\
AppBindData data = new AppBindData();
data.processName = processName;
data.appInfo = appInfo;
data.providers = providerList.getList();
...
sendMessage(H.BIND_APPLICATION, data);
- ActivityThread中的handleMessage()方法
主線(xiàn)程H接收bindApplication發(fā)送的BIND_APPLICATION消息挠锥,在handleMessage()方法中處理應(yīng)用程序綁定众羡;
- 調(diào)用Trace.traceBegin()方法開(kāi)始跟蹤,傳入的參數(shù)為T(mén)race.TRACE_TAG_ACTIVITY_MANAGER和"bindApplication"蓖租,用于標(biāo)識(shí)跟蹤的標(biāo)簽和操作粱侣;
- 從msg對(duì)象中獲取AppBindData類(lèi)型的數(shù)據(jù),并將其賦值給data變量蓖宦;
- 調(diào)用handleBindApplication(data)方法處理應(yīng)用程序綁定齐婴;
- 調(diào)用Trace.traceEnd()方法結(jié)束跟蹤;
class H extends Handler {
...
public void handleMessage(Message msg) {
if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
switch (msg.what) {
case BIND_APPLICATION:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
AppBindData data = (AppBindData)msg.obj;
handleBindApplication(data);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
...
- ActivityThread中的handleBindApplication()方法
handleBindApplication()方法用來(lái)處理應(yīng)用程序綁定稠茂,該方法初始化了Android的上下文環(huán)境柠偶,同時(shí)還初始化了Application,并且回調(diào)了Application的onCreat()方法睬关。其中關(guān)鍵代碼行:
- 從AppBindData對(duì)象中獲取應(yīng)用程序的包名和類(lèi)名诱担;
- 根據(jù)包名和類(lèi)名創(chuàng)建一個(gè)新的應(yīng)用程序?qū)嵗⑵滟x值給mInitialApplication變量电爹;
- 調(diào)用installContentProviders()方法安裝應(yīng)用程序的內(nèi)容提供者蔫仙。
- 調(diào)用mInstrumentation.callApplicationOnCreate()方法調(diào)用應(yīng)用程序的onCreate()方法;
- 調(diào)用scheduleGcIdler()方法安排垃圾回收器運(yùn)行藐不;
private void handleBindApplication(AppBindData data) {
...
Process.setArgV0(data.processName);
...
VMRuntime.setProcessPackageName(data.appInfo.packageName);
...
final ContextImpl instrContext = ContextImpl.createAppContext(this, pi,
appContext.getOpPackageName());
try {
final ClassLoader cl = instrContext.getClassLoader();
mInstrumentation = (Instrumentation)
cl.loadClass(data.instrumentationName.getClassName()).newInstance();
} catch (Exception e) {
...
}
final ComponentName component = new ComponentName(ii.packageName, ii.name);
mInstrumentation.init(this, instrContext, appContext, component,
data.instrumentationWatcher, data.instrumentationUiAutomationConnection);
...
Application app;
...
try {
app = data.info.makeApplication(data.restrictedBackupMode, null);
app.setAutofillOptions(data.autofillOptions);
app.setContentCaptureOptions(data.contentCaptureOptions);
mInitialApplication = app;
if (!data.restrictedBackupMode) {
if (!ArrayUtils.isEmpty(data.providers)) {
installContentProviders(app, data.providers);
}
}
try {
mInstrumentation.onCreate(data.instrumentationArgs);
}
catch (Exception e) {
...
}
try {
mInstrumentation.callApplicationOnCreate(app);
} catch (Exception e) {
...
}
- RootWindowContainer中的startActivityForAttachedApplicationIfNeeded()方法
在執(zhí)行完bindApplication之后匀哄,流程會(huì)繼續(xù)在主線(xiàn)程中運(yùn)行秦效,回到AMS的attachApplicationLocked()方法中繼續(xù)往下執(zhí)行,調(diào)用ATMS中的attachApplication()方法涎嚼,然后調(diào)用到RootWindowContainer中的attachApplication()方法阱州,再走到RootWindowContainer的startActivityForAttachedApplicationIfNeeded()方法中找到與此進(jìn)程相關(guān)聯(lián)的Activity,并打開(kāi)此Activity法梯;
- 首先檢查ActivityRecord (目標(biāo)Activity在A(yíng)MS中的數(shù)據(jù)結(jié)構(gòu))苔货;
- 調(diào)用mStackSupervisor.realStartActivityLocked()方法來(lái)啟動(dòng)活動(dòng);
private boolean startActivityForAttachedApplicationIfNeeded(ActivityRecord r,
WindowProcessController app, ActivityRecord top) {
if (r.finishing || !r.okToShowLocked() || !r.visibleIgnoringKeyguard || r.app != null
|| app.mUid != r.info.applicationInfo.uid || !app.mName.equals(r.processName)) {
return false;
}
try {
if (mStackSupervisor.realStartActivityLocked(r, app, top == r /*andResume*/,
true /*checkConfig*/)) {
mTmpBoolean = true;
}
} catch (RemoteException e) {
Slog.w(TAG, "Exception in new application when starting activity "
+ top.intent.getComponent().flattenToShortString(), e);
mTmpRemoteException = e;
return true;
}
return false;
}
- ActivityStackSupervisor中的realStartActivityLocked()方法
ActivityStackSupervisor中的realStartActivityLocked()方法在A(yíng)ctivityStackSupervisor中的startSpecificActivity()中也有調(diào)用立哑,① startSpecificActivity()方法中如果目標(biāo)Activity的進(jìn)程已經(jīng)啟動(dòng)就會(huì)走到realStartActivityLocked()中啟動(dòng)目標(biāo)Activity夜惭,② 而目標(biāo)Activity的進(jìn)程沒(méi)有啟動(dòng)的情況,通過(guò)AMS創(chuàng)建了新的進(jìn)程啟動(dòng)铛绰,同樣走到realStartActivityLocked()中啟動(dòng)目標(biāo)Activity诈茧;
realStartActivityLocked() 方法在 Activity 的啟動(dòng)過(guò)程中處理 Activity 的創(chuàng)建、生命周期的管理捂掰,處理與任務(wù)和堆棧相關(guān)的邏輯敢会,進(jìn)行必要的配置檢查,確保 Activity 能夠正確無(wú)誤地啟動(dòng)这嚣;
- 調(diào)用r.startFreezingScreenLocked(proc, 0)暫停屏幕凍結(jié)鸥昏。
- 調(diào)用r.startLaunchTickingLocked()啟動(dòng)計(jì)時(shí)器以收集關(guān)于慢應(yīng)用程序的信息。
- 設(shè)置進(jìn)程r.setProcess(proc)姐帚。
- 如果需要恢復(fù)Activity吏垮,確保Activity允許恢復(fù)r.canResumeByCompat()。
- 通知未知的可見(jiàn)性啟動(dòng)關(guān)鍵鎖過(guò)渡r.notifyUnknownVisibilityLaunchedForKeyguardTransition()罐旗。
- 檢查配置膳汪,如果需要,確保Activity的可見(jiàn)性和配置r.ensureVisibilityAndConfig()尤莺。
- 根據(jù)新的Activity順序重新評(píng)估屏幕方向旅敷。
- 更新Home進(jìn)程。
- 通知包使用情況mService.getPackageManagerInternalLocked().notifyPackageUse()颤霎。
- 設(shè)置Activity為非休眠狀態(tài)r.setSleeping(false)。
- 獲取Activity的兼容性信息r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo)涂滴。
- 創(chuàng)建一個(gè)新的合并配置MergedConfiguration友酱。
- 記錄過(guò)大的交易日志logIfTransactionTooLarge(r.intent, r.getSavedState())。
- 創(chuàng)建Activity啟動(dòng)事務(wù)ClientTransaction柔纵。
- 設(shè)置期望的最終狀態(tài)缔杉,根據(jù)andResume的值選擇ResumeActivityItem或PauseActivityItem。
- 調(diào)度事務(wù)mService.getLifecycleManager()搁料。
- 檢查標(biāo)志和mService.mHasHeavyWeightFeature是否為真或详,如果滿(mǎn)足系羞,說(shuō)明這個(gè)進(jìn)程可能是一個(gè)"heavy-weight process"。
- 檢查了proc.mName是否等于proc.mInfo.packageName霸琴,確保只有主進(jìn)程可以運(yùn)行在.apk文件中的Activity椒振,因?yàn)橹挥蠥ctivity才會(huì)被認(rèn)為是"heavy-weight"。
- 檢查mService.mHeavyWeightProcess是否已經(jīng)存在且不等于當(dāng)前進(jìn)程proc梧乘,如果是表示在啟動(dòng)一個(gè)新的"heavy-weight process"的時(shí)候已經(jīng)有一個(gè)正在運(yùn)行的"heavy-weight process"澎迎,打印警告日志。
- 調(diào)用setHeavyWeightProcess()設(shè)置當(dāng)前的Activity記錄r作為"heavy-weight process"选调。
- 將r.launchFailed設(shè)置為false夹供,表示啟動(dòng)失敗的狀態(tài)已經(jīng)被清除,如果需要恢復(fù)且系統(tǒng)已經(jīng)準(zhǔn)備好恢復(fù)仁堪,調(diào)用minimalResumeActivityLocked來(lái)恢復(fù)這個(gè)Activity哮洽,否則將這個(gè)Activity的狀態(tài)設(shè)置為PAUSED,并執(zhí)行一個(gè)應(yīng)用程序過(guò)渡弦聂。
- 調(diào)用onStartActivity更新進(jìn)程的狀態(tài)鸟辅。
- 如果當(dāng)前的棧是頂部顯示的焦點(diǎn)棧,它將啟動(dòng)一個(gè)新的版本設(shè)置屏幕横浑,因?yàn)樵趩?dòng)初始Activity之后啟動(dòng)這個(gè)設(shè)置屏幕剔桨,可以讓它在后臺(tái)初始化自己,這樣當(dāng)切換回它時(shí)速度更快徙融。
- 如果這個(gè)Activity屬于一個(gè)應(yīng)用洒缀,將更新與這個(gè)應(yīng)用綁定的任何可能關(guān)心其客戶(hù)端是否有活動(dòng)的服務(wù)。
- 返回true表示Activity已經(jīng)成功啟動(dòng)欺冀。
realStartActivityLocked()方法找到與進(jìn)程相關(guān)聯(lián)的Activity树绩,這里的ClientTransaction具備IPC的能力,通過(guò)內(nèi)部的IApplicationThread Binder接口隐轩,會(huì)把自己作為參數(shù)傳遞給對(duì)應(yīng)要操作的進(jìn)程饺饭。本次的事務(wù)處理,ClientTransaction添加了一個(gè)LaunchActivityItem职车,說(shuō)明要顯示Activity的意圖瘫俊,打開(kāi)目標(biāo)Activity。
boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
boolean andResume, boolean checkConfig) throws RemoteException {
...
final DisplayContent dc = r.getDisplay().mDisplayContent;
clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
System.identityHashCode(r), r.info,
// TODO: Have this take the merged configuration instead of separate global
// and override configs.
mergedConfiguration.getGlobalConfiguration(),
mergedConfiguration.getOverrideConfiguration(), r.compat,
r.launchedFromPackage, task.voiceInteractor, proc.getReportedProcState(),
r.getSavedState(), r.getPersistentSavedState(), results, newIntents,
dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(),
r.assistToken, r.createFixedRotationAdjustmentsIfNeeded()));
...
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
- ActivityThread中的ApplicationThread 類(lèi)
應(yīng)用進(jìn)程會(huì)收到ClientTransaction的方法回調(diào)悴灵;
ApplicationThread 類(lèi)在 ActivityThread 中的作用是作為與系統(tǒng)其他部分通信的橋梁扛芽,處理應(yīng)用的生命周期事件,并在UI線(xiàn)程上協(xié)調(diào)操作积瞒,以及參與應(yīng)用的啟動(dòng)過(guò)程川尖;
- 作為Binder通信的端點(diǎn):ApplicationThread 是一個(gè) Binder 服務(wù)端點(diǎn),用于與系統(tǒng)的其他部分進(jìn)行通信茫孔,這種通信機(jī)制允許跨進(jìn)程調(diào)用叮喳,從而使得系統(tǒng)能夠?qū)?yīng)用的生命周期事件進(jìn)行調(diào)度和管理被芳。
- 處理應(yīng)用程序的生命周期事件:ApplicationThread 通過(guò) scheduleTransaction 方法接收來(lái)自AMS的指令,包括啟動(dòng)馍悟、暫团媳簦或銷(xiāo)毀 Activity 等生命周期事件,ActivityThread 就能夠響應(yīng)這些事件并做出相應(yīng)的處理赋朦。
- 協(xié)調(diào)UI線(xiàn)程的操作: ActivityThread 是運(yùn)行在主線(xiàn)程上的篓冲,ApplicationThread 類(lèi)負(fù)責(zé)確保所有與UI相關(guān)的操作都在正確的線(xiàn)程上執(zhí)行。
- 參與應(yīng)用的啟動(dòng)過(guò)程:在應(yīng)用啟動(dòng)時(shí)宠哄,ActivityThread 的 main 方法會(huì)被調(diào)用壹将,而 ApplicationThread 則參與到這一過(guò)程中,例如在 startActivityForResult 方法中調(diào)用 Instrumentation 的 execStartActivity 方法時(shí)毛嫉,會(huì)涉及到 mMainThread诽俯,即 ActivityThread 的一個(gè)實(shí)例。
private class ApplicationThread extends IApplicationThread.Stub {
...
@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
ActivityThread.this.scheduleTransaction(transaction);
}
...
}
...
private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
Message msg = Message.obtain();
msg.what = what;
msg.obj = obj;
msg.arg1 = arg1;
msg.arg2 = arg2;
if (async) {
msg.setAsynchronous(true);
}
mH.sendMessage(msg);
}
- TransactionExecutor的executeCallbacks類(lèi)
在接收到scheduleTransaction的回調(diào)之后承粤,還是會(huì)把消息給到ActivityThread的H處理暴区,H會(huì)把ClientTransaction這個(gè)消息給到TransactionExecutor處理;
TransactionExecutor的作用是確毙岭客戶(hù)端事務(wù)(如啟動(dòng)仙粱、暫停或銷(xiāo)毀 Activity)能夠按照正確的順序和時(shí)機(jī)被執(zhí)行彻舰;
- 執(zhí)行回調(diào):TransactionExecutor 通過(guò)其 execute 方法來(lái)執(zhí)行事務(wù)伐割,首先會(huì)執(zhí)行所有的回調(diào)(callbacks),這些回調(diào)通常是與生命周期事件相關(guān)的操作刃唤,比如 onCreate隔心、onPause 等。
- 管理生命周期:在執(zhí)行完回調(diào)之后尚胞,TransactionExecutor 會(huì)管理 Activity 的生命周期硬霍,確保 Activity 在不同的生命周期階段執(zhí)行相應(yīng)的邏輯。
- 清理操作:最后笼裳,TransactionExecutor 會(huì)清理 mPendingActions唯卖,可能涉及到移除已經(jīng)處理過(guò)或者不再需要的操作項(xiàng)。
executeCallbacks 方法在 TransactionExecutor 類(lèi)中的作用是執(zhí)行所有掛起的回調(diào)(Callbacks)躬柬,會(huì)遍歷 mPendingActions 列表耐床,包含了所有待執(zhí)行的操作(通常是與 Activity 生命周期相關(guān)的操作,如 onPause()楔脯、onResume() 等),executeCallbacks 方法會(huì)依次執(zhí)行這些操作胯甩,并從列表中移除已執(zhí)行的操作昧廷。
- 啟動(dòng) Activity:當(dāng)一個(gè)新 Activity 被啟動(dòng)時(shí)堪嫂,與之相關(guān)的回調(diào)會(huì)被添加到 mPendingActions 中,并在適當(dāng)?shù)臅r(shí)候由 executeCallbacks 方法執(zhí)行木柬。
- 恢復(fù) Activity:當(dāng)一個(gè)暫停的 Activity 被恢復(fù)時(shí)皆串,與之相關(guān)的回調(diào)也會(huì)通過(guò) executeCallbacks 方法執(zhí)行。
- 銷(xiāo)毀 Activity:當(dāng)一個(gè) Activity 被銷(xiāo)毀時(shí)眉枕,清理操作也會(huì)通過(guò) executeCallbacks 方法來(lái)執(zhí)行恶复。
TransactionExecutor會(huì)去執(zhí)行ClientTransactionItem 內(nèi)部的邏輯;
public void executeCallbacks(ClientTransaction transaction) {
final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
...
for (int i = 0; i < size; ++i) {
final ClientTransactionItem item = callbacks.get(i);
if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "Resolving callback: " + item);
final int postExecutionState = item.getPostExecutionState();
final int closestPreExecutionState = mHelper.getClosestPreExecutionState(r,
item.getPostExecutionState());
if (closestPreExecutionState != UNDEFINED) {
cycleToPath(r, closestPreExecutionState, transaction);
}
item.execute(mTransactionHandler, token, mPendingActions);
item.postExecute(mTransactionHandler, token, mPendingActions);
...
- LaunchActivityItem類(lèi)
LaunchActivityItem類(lèi)的是用于啟動(dòng) Activity 的一個(gè)內(nèi)部類(lèi)速挑,作用是作為消息對(duì)象來(lái)啟動(dòng) Activity谤牡。 在 Android 的應(yīng)用程序框架中,ActivityThread 負(fù)責(zé)管理應(yīng)用程序進(jìn)程中主線(xiàn)程的執(zhí)行姥宝,而 LaunchActivityItem 則是它處理的消息之一翅萤。當(dāng)系統(tǒng)需要啟動(dòng)一個(gè)新的 Activity 時(shí),AMS會(huì)創(chuàng)建 LaunchActivityItem 并將其發(fā)送給目標(biāo)應(yīng)用的 ActivityThread腊满,ActivityThread會(huì)調(diào)用 LaunchActivityItem 的 execute() 方法來(lái)實(shí)際啟動(dòng) Activity套么。
LaunchActivityItem中的execute方法的作用是執(zhí)行一個(gè)Activity的啟動(dòng)操作;
- 通過(guò)調(diào)用Trace.traceBegin方法開(kāi)始跟蹤Activity的啟動(dòng)過(guò)程碳蛋;
- 創(chuàng)建一個(gè)ActivityClientRecord對(duì)象r胚泌,該對(duì)象包含了啟動(dòng)Activity所需的各種信息,如Intent肃弟、標(biāo)識(shí)符玷室、配置等;
- 調(diào)用client.handleLaunchActivity方法來(lái)處理Activity的啟動(dòng)愕乎,傳入r阵苇、pendingActions和null作為參數(shù);
- 通過(guò)調(diào)用Trace.traceEnd方法結(jié)束跟蹤感论。
execute中的client參數(shù)就是ActivityThread绅项,ActivityThread實(shí)現(xiàn)了ClientTransactionHandler,這里就調(diào)用到了ActivityThread的handleLaunchActivity方法比肄,同時(shí)把Activity的相關(guān)信息封裝成了ActivityClientRecord 數(shù)據(jù)結(jié)構(gòu)作為參數(shù)傳遞快耿;
public class LaunchActivityItem extends ClientTransactionItem {
...
@Override
public void execute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
mPendingResults, mPendingNewIntents, mIsForward,
mProfilerInfo, client, mAssistToken, mFixedRotationAdjustments);
client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
...
- ActivityThread中的handleLaunchActivity()方法
該方法主要功能是處理啟動(dòng)Activity的操作:
- 首先,調(diào)用unscheduleGcIdler()方法取消垃圾回收的調(diào)度芳绩。
- 設(shè)置mSomeActivitiesChanged為true掀亥,表示有活動(dòng)發(fā)生了變化。
- 如果r.profilerInfo不為空妥色,則設(shè)置Profiler并開(kāi)始分析搪花。
- 確保運(yùn)行的是最新的配置,如果需要的話(huà)預(yù)加載硬件渲染器。
- 初始化WindowManagerGlobal撮竿。
- 提示GraphicsEnvironment一個(gè)進(jìn)程上的活動(dòng)正在啟動(dòng)吮便。
- 調(diào)用performLaunchActivity方法執(zhí)行實(shí)際的啟動(dòng)操作,并將返回的Activity對(duì)象賦值給變量a幢踏。
- 如果a不為空髓需,則進(jìn)行以下操作:
創(chuàng)建一個(gè)新的Configuration對(duì)象,并將其賦值給r.createdConfig房蝉。
報(bào)告尺寸配置信息僚匆。
如果r.activity未完成且pendingActions不為空,則設(shè)置pendingActions的舊狀態(tài)搭幻、恢復(fù)實(shí)例狀態(tài)和調(diào)用onPostCreate標(biāo)志咧擂。 - 如果a為空,則表示有錯(cuò)誤發(fā)生粗卜,通知ActivityManager停止當(dāng)前進(jìn)程屋确。
- 最后,返回Activity對(duì)象a续扔。
public Activity handleLaunchActivity(ActivityClientRecord r,
PendingTransactionActions pendingActions, Intent customIntent) {
// If we are getting ready to gc after going to the background, well
// we are back active so skip it.
unscheduleGcIdler();
mSomeActivitiesChanged = true;
if (r.profilerInfo != null) {
mProfiler.setProfiler(r.profilerInfo);
mProfiler.startProfiling();
}
// Make sure we are running with the most recent config.
handleConfigurationChanged(null, null);
if (localLOGV) Slog.v(
TAG, "Handling launch of " + r);
// Initialize before creating the activity
if (!ThreadedRenderer.sRendererDisabled
&& (r.activityInfo.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0) {
HardwareRenderer.preload();
}
WindowManagerGlobal.initialize();
// Hint the GraphicsEnvironment that an activity is launching on the process.
GraphicsEnvironment.hintActivityLaunch();
final Activity a = performLaunchActivity(r, customIntent);
if (a != null) {
r.createdConfig = new Configuration(mConfiguration);
reportSizeConfigurations(r);
if (!r.activity.mFinished && pendingActions != null) {
pendingActions.setOldState(r.state);
pendingActions.setRestoreInstanceState(true);
pendingActions.setCallOnPostCreate(true);
}
} else {
// If there was an error, for any reason, tell the activity manager to stop us.
try {
ActivityTaskManager.getService()
.finishActivity(r.token, Activity.RESULT_CANCELED, null,
Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
}
return a;
}
- ActivityThread的performLaunchActivity()方法
performLaunchActivity方法執(zhí)行實(shí)際的啟動(dòng)Activity操作攻臀,負(fù)責(zé)啟動(dòng)一個(gè) Activity,并返回該 Activity 的實(shí)例纱昧;
- 首先會(huì)調(diào)用Activity的onCreate方法來(lái)創(chuàng)建Activity實(shí)例刨啸;
- 根據(jù)傳入的Intent對(duì)象,可能會(huì)進(jìn)行一些額外的處理识脆,例如啟動(dòng)其他Activity设联、發(fā)送廣播等;
- 將創(chuàng)建的Activity實(shí)例返回給調(diào)用者灼捂。
- 獲取 Activity 信息:從傳入的 ActivityClientRecord 對(duì)象中獲取 Activity 的信息离例,包括包名、組件名等悉稠。
- 創(chuàng)建 Activity 實(shí)例:通過(guò)反射機(jī)制宫蛆,使用 Instrumentation的newActivity方法創(chuàng)建 Activity 的實(shí)例。
- 準(zhǔn)備 Activity 上下文:創(chuàng)建一個(gè)應(yīng)用程序上下文(ContextImpl)用于 Activity 的運(yùn)行環(huán)境的猛。
- 初始化 Activity:調(diào)用 makeApplication() 方法創(chuàng)建一個(gè)應(yīng)用程序?qū)嵗粒?Activity 與應(yīng)用程序關(guān)聯(lián)起來(lái)。
- 設(shè)置 Activity 屬性:根據(jù) Activity 的屬性和配置卦尊,設(shè)置 Activity 的主題叛拷、窗口模式等。
- 調(diào)用 Activity 生命周期方法:調(diào)用 callActivityOnCreate() 方法岂却,執(zhí)行 Activity 的 onCreate() 方法忿薇。
- 處理異常:如果在啟動(dòng)過(guò)程中發(fā)生異常裙椭,會(huì)通過(guò) Instrumentation 的 onException() 方法進(jìn)行處理。
- 返回 Activity 實(shí)例:最后煌恢,返回創(chuàng)建好的 Activity 實(shí)例骇陈。
performLaunchActivity方法只是執(zhí)行啟動(dòng)Activity的操作,具體的生命周期管理瑰抵、消息傳遞等功能是由ActivityThread類(lèi)的其他方法來(lái)完成的。
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
ActivityInfo aInfo = r.activityInfo;
if (r.packageInfo == null) {
r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
Context.CONTEXT_INCLUDE_CODE);
}
ComponentName component = r.intent.getComponent();
if (component == null) {
component = r.intent.resolveActivity(
mInitialApplication.getPackageManager());
r.intent.setComponent(component);
}
if (r.activityInfo.targetActivity != null) {
component = new ComponentName(r.activityInfo.packageName,
r.activityInfo.targetActivity);
}
ContextImpl appContext = createBaseContextForActivity(r);
Activity activity = null;
try {
java.lang.ClassLoader cl = appContext.getClassLoader();
// AppComponentFactory利用反射生成Activity
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
StrictMode.incrementExpectedActivityCount(activity.getClass());
r.intent.setExtrasClassLoader(cl);
r.intent.prepareToEnterProcess();
if (r.state != null) {
r.state.setClassLoader(cl);
}
} catch (Exception e) {
if (!mInstrumentation.onException(activity, e)) {
throw new RuntimeException(
"Unable to instantiate activity " + component
+ ": " + e.toString(), e);
}
}
try {
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
if (localLOGV) Slog.v(
TAG, r + ": app=" + app
+ ", appName=" + app.getPackageName()
+ ", pkg=" + r.packageInfo.getPackageName()
+ ", comp=" + r.intent.getComponent().toShortString()
+ ", dir=" + r.packageInfo.getAppDir());
if (activity != null) {
CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Configuration config = new Configuration(mCompatConfiguration);
if (r.overrideConfig != null) {
config.updateFrom(r.overrideConfig);
}
if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
+ r.activityInfo.name + " with config " + config);
Window window = null;
if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
window = r.mPendingRemoveWindow;
r.mPendingRemoveWindow = null;
r.mPendingRemoveWindowManager = null;
}
// Activity resources must be initialized with the same loaders as the
// application context.
appContext.getResources().addLoaders(
app.getResources().getLoaders().toArray(new ResourcesLoader[0]));
appContext.setOuterContext(activity);
// activity關(guān)聯(lián)相關(guān)的信息器联,包括創(chuàng)建PhoneWindow
activity.attach(appContext, this, getInstrumentation(), r.token,
r.ident, app, r.intent, r.activityInfo, title, r.parent,
r.embeddedID, r.lastNonConfigurationInstances, config,
r.referrer, r.voiceInteractor, window, r.configCallback,
r.assistToken);
if (customIntent != null) {
activity.mIntent = customIntent;
}
r.lastNonConfigurationInstances = null;
checkAndBlockForNetworkAccess();
activity.mStartedActivity = false;
int theme = r.activityInfo.getThemeResource();
if (theme != 0) {
activity.setTheme(theme);
}
activity.mCalled = false;
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
// 回調(diào)Activity的OnCreate回調(diào)方法
mInstrumentation.callActivityOnCreate(activity, r.state);
}
if (!activity.mCalled) {
throw new SuperNotCalledException(
"Activity " + r.intent.getComponent().toShortString() +
" did not call through to super.onCreate()");
}
r.activity = activity;
mLastReportedWindowingMode.put(activity.getActivityToken(),
config.windowConfiguration.getWindowingMode());
}
r.setState(ON_CREATE);
// updatePendingActivityConfiguration() reads from mActivities to update
// ActivityClientRecord which runs in a different thread. Protect modifications to
// mActivities to avoid race.
synchronized (mResourcesManager) {
mActivities.put(r.token, r);
}
} catch (SuperNotCalledException e) {
throw e;
} catch (Exception e) {
if (!mInstrumentation.onException(activity, e)) {
throw new RuntimeException(
"Unable to start activity " + component
+ ": " + e.toString(), e);
}
}
return activity;
}
在回調(diào)了Activity的OnCreate方法之后二汛,目標(biāo)Activity就創(chuàng)建完成了。
Activity創(chuàng)建過(guò)程總結(jié)
- 當(dāng)某個(gè)Activity要跳轉(zhuǎn)到另一個(gè)Activity時(shí)拨拓,會(huì)發(fā)起startActivity肴颊,走到Activity中的startActivity()方法中,startActivity()方法主要作用是移除當(dāng)前活動(dòng)的恢復(fù)能力渣磷,暫停當(dāng)前活動(dòng)婿着,并將恢復(fù)能力添加到目標(biāo)Activity的Intent意圖中,然后走到Activity的startActivityForResult()方法中醋界;
- Activity中的startActivityForResult()方法的作用是在當(dāng)前Activity中啟動(dòng)一個(gè)新的Activity竟宋,當(dāng)新的Activity結(jié)束后會(huì)通過(guò)ActivityThread.sendActivityResult()方法將活動(dòng)啟動(dòng)結(jié)果發(fā)送給啟動(dòng)新活動(dòng)的父活動(dòng),startActivityForResult()方法中啟動(dòng)新Activity的操作會(huì)走到Instrumentation中的execStartActivity()方法形纺;
- Instrumentation中的execStartActivity()啟動(dòng)新的Activity有兩種情況丘侠,① 當(dāng)系統(tǒng)存在活動(dòng)監(jiān)視器,且忽略匹配特殊意圖時(shí)逐样,新的Activity會(huì)通過(guò)ActivityMonitor的onStartActivity()方法啟動(dòng)蜗字;② 其他情況都是通過(guò)調(diào)用ActivityTaskManagerService中的startActivityAsUser()方法來(lái)啟動(dòng)新的Activity的;
- 到這里脂新,啟動(dòng)新Activity的流程就從Activity中走到了系統(tǒng)服務(wù)器中挪捕。ActivityTaskManagerService中的startActivityAsUser()方法主要作用是以特定用戶(hù)身份啟動(dòng)一個(gè)新的Activity,startActivityAsUser()方法會(huì)接收13個(gè)參數(shù)争便,中間進(jìn)行一些處理级零,方法最后會(huì)通過(guò)ActivityStartController的obtainStarter()方法創(chuàng)建一個(gè)活動(dòng)啟動(dòng)器Starter對(duì)象,通過(guò)鏈?zhǔn)秸{(diào)用來(lái)設(shè)置Intent意圖等參數(shù)始花,最后調(diào)用ActivityStarter的execute()方法執(zhí)行Activity的啟動(dòng)操作妄讯;
- ActivityStarter是一個(gè)控制器,負(fù)責(zé)解釋解釋如何在特定的時(shí)間和方式下啟動(dòng)一個(gè)Activity酷宵,ActivityStarter中的execute()作為外部接口亥贸,觸發(fā)整個(gè)啟動(dòng)過(guò)程,而新Activity的具體的啟動(dòng)邏輯和記錄創(chuàng)建會(huì)走到ActivityStarter中的executeRequest()方法中執(zhí)行浇垦;
- ActivityStarter中的executeRequest()方法主要作用是處理啟動(dòng)Activity請(qǐng)求炕置,創(chuàng)建Activity對(duì)應(yīng)的ActivityRecord(目標(biāo)Activity在A(yíng)MS中的數(shù)據(jù)結(jié)構(gòu)),將記錄存儲(chǔ)在任務(wù)Task中,然后調(diào)用ActivityStarter中的startActivityUnchecked()方法來(lái)啟動(dòng)新的Activity朴摊;
- ActivityStarter中的startActivityUnchecked()方法主要處理與客戶(hù)端相關(guān)的邏輯默垄,處理啟動(dòng)Activity的前期準(zhǔn)備工作(傳遞參數(shù)、處理生命周期)甚纲,新的Activity啟動(dòng)與系統(tǒng)服務(wù)進(jìn)程的交互會(huì)走到ActivityStarter中的startActivityInner()方法中進(jìn)行口锭;
- ActivityStarter中的startActivityInner()方法處理了啟動(dòng)Activity所需的各種參數(shù)和邏輯,包括任務(wù)棧管理介杆、權(quán)限檢查鹃操、URI權(quán)限授予、任務(wù)記錄等春哨,新啟動(dòng)的Activity的Task和Activity進(jìn)棧處理會(huì)走到ActivityStack中的startActivityLocked()方法中荆隘,新的Activity的啟動(dòng)則會(huì)調(diào)用RootWindowContainer中的resumeFocusedStacksTopActivities()方法;
- ActivityStack中的startActivityLocked()方法的作用主要是負(fù)責(zé)將待啟動(dòng)的Activity對(duì)應(yīng)的ActivityRecord對(duì)象入棧赴背,椰拒,確保新Activity按照正確的順序被添加到任務(wù)棧中,以便用戶(hù)可以通過(guò)按返回鍵來(lái)導(dǎo)航Activity歷史記錄凰荚;
- RootWindowContainer中的resumeFocusedStacksTopActivities()方法的作用是恢復(fù)焦點(diǎn)棧頂部的Activity燃观,會(huì)調(diào)用ActivityStack中的resumeTopActivityUncheckedLocked()方法將當(dāng)前處于焦點(diǎn)狀態(tài)的Activity恢復(fù)到棧頂,成為用戶(hù)界面可見(jiàn)和可交互的狀態(tài)浇揩;
- ActivityStack中的resumeTopActivityUncheckedLocked()方法會(huì)恢復(fù)棧頂?shù)腁ctivity實(shí)例仪壮,使其進(jìn)入活動(dòng)狀態(tài),會(huì)調(diào)用resumeTopActivityInnerLocked()方法來(lái)恢復(fù)棧頂?shù)腁ctivity胳徽,并做一些恢復(fù)后的處理操作积锅;
- ActivityStack中的resumeTopActivityInnerLocked()方法的作用是恢復(fù)棧頂?shù)腁ctivity實(shí)例,使目標(biāo)Activity進(jìn)入活動(dòng)狀態(tài)养盗,并確保其可見(jiàn)性缚陷,其中調(diào)用startPausingLocked() 方法對(duì)當(dāng)前運(yùn)行的 Activity(發(fā)起者 Activity)觸發(fā) Pause 動(dòng)作,并執(zhí)行 startSpecificActivity()進(jìn)一步處理目標(biāo) Activity 的啟動(dòng)和恢復(fù)過(guò)程往核;
- ActivityStackSupervisor中的startSpecificActivity()方法主要用來(lái)啟動(dòng)或恢復(fù)目標(biāo)Activity實(shí)例箫爷,如果目標(biāo)Activity的進(jìn)程已經(jīng)啟動(dòng),調(diào)用realStartActivityLocked() 方法來(lái)恢復(fù)該 Activity聂儒,否則調(diào)用ATMS的startProcessAsync異步地啟動(dòng)目標(biāo)Activity虎锚;
- ActivityTaskManagerService中的startProcessAsync()方法的作用是給AMS發(fā)送一條創(chuàng)建新進(jìn)程的消息,創(chuàng)建目標(biāo)Activity對(duì)應(yīng)的進(jìn)程衩婚,發(fā)送的消息包含啟動(dòng)進(jìn)程所需要的所有信息窜护;
- 創(chuàng)建新進(jìn)程的消息從ATMS發(fā)送到AMS中,被ActivityManagerService中的startProcessLocked()方法接收非春,直接傳入ProcessList中的startProcessLocked()方法中柱徙;
- ProcessList中的startProcessLocked()方法對(duì)傳入的14個(gè)參數(shù)進(jìn)行一系列處理缓屠,最后根據(jù)系統(tǒng)配置,可以同步或異步啟動(dòng)線(xiàn)程护侮,同步啟動(dòng)線(xiàn)程會(huì)調(diào)用ProcessList中的startProcess()方法來(lái)啟動(dòng)一個(gè)新進(jìn)程敌完;
- ProcessList中的startProcess()方法會(huì)創(chuàng)建一個(gè)AppZygote對(duì)象,孵化出新的進(jìn)程羊初,然后調(diào)用AppZygote.Process的start方法來(lái)啟動(dòng)新進(jìn)程滨溉,新Activity對(duì)應(yīng)的進(jìn)程的創(chuàng)建和啟動(dòng)完成,接下來(lái)就是應(yīng)用進(jìn)程啟動(dòng)之后的操作凳忙,流程走到了ActivityThread中业踏;
- 應(yīng)用程序啟動(dòng)時(shí),系統(tǒng)會(huì)調(diào)用ActivityThread中的主函數(shù)main()來(lái)創(chuàng)建ActivityThread實(shí)例涧卵,并調(diào)用attach()方法將該實(shí)例與當(dāng)前應(yīng)用程序關(guān)聯(lián),然后調(diào)用AMS中的startActivity()方法啟動(dòng)應(yīng)用程序的主Activity腹尖,這個(gè)流程又會(huì)走到ATMS的startActvityAsUser()方法中柳恐,與前面的流程一樣,不過(guò)會(huì)走目標(biāo)Activity對(duì)應(yīng)的進(jìn)程已存在的情況了热幔;
- ActivityThread中的attach()方法的作用是想AMS注冊(cè)目標(biāo)Activity對(duì)應(yīng)的進(jìn)程乐设,會(huì)調(diào)用ActivityManager的attachApplication方法將應(yīng)用程序綁定到AMS,并傳遞IApplicationThreadBinder對(duì)象以便于系統(tǒng)能夠?qū)Ρ具M(jìn)程進(jìn)行調(diào)度和管理绎巨;
- ActivityManagerService中的attachApplication()方法的作用是為應(yīng)用創(chuàng)建必要的環(huán)境近尚,如創(chuàng)建進(jìn)程狀態(tài)記錄、分配進(jìn)程ID等场勤,并調(diào)用AMS的attachApplicationLocked()方法將應(yīng)用程序綁定到AMS中戈锻;
- ActivityManagerService中的attachApplicationLocked()方法負(fù)責(zé)創(chuàng)建和管理應(yīng)用的全局狀態(tài),確保應(yīng)用進(jìn)程與系統(tǒng)服務(wù)之間的正確通信和媳,該方法會(huì)創(chuàng)建一個(gè)AppDeathRecipient對(duì)象并將其與ActivityThread的Binder對(duì)象關(guān)聯(lián)來(lái)注冊(cè)進(jìn)程死亡回調(diào)格遭,確保當(dāng)應(yīng)用程序的進(jìn)程意外終止時(shí),AMS能夠及時(shí)得知并做出相應(yīng)處理留瞳,除此之外還調(diào)用了ActivityThread的bindApplication()方法來(lái)啟動(dòng)應(yīng)用程序的Application對(duì)象拒迅,以此開(kāi)啟應(yīng)用級(jí)操作;
- ActivityThread中的bindApplication()方法負(fù)責(zé)將應(yīng)用程序的 Application 對(duì)象與操作系統(tǒng)進(jìn)行綁定她倘,并完成一系列的初始化工作璧微,接收來(lái)在A(yíng)MS的綁定信息,經(jīng)過(guò)一些處理后給主線(xiàn)程Handler H 發(fā)送送一條信息硬梁,進(jìn)程接收到的信息交由H處理前硫,在A(yíng)ctivityThread中的handleMessage()方法中進(jìn)行消息處理;
- ActivityThread中的handleMessage()方法主要用于處理應(yīng)用程序綁定和方法跟蹤處理靶溜,處理應(yīng)用程序綁定會(huì)調(diào)用ActivityThread中的handleBindApplication()方法進(jìn)行對(duì)應(yīng)操作开瞭;
- ActivityThread中的handleBindApplication()方法處理應(yīng)用程序綁定懒震,初始化Android的上下文環(huán)境和Application,并回調(diào)了Application的onCreate()方法嗤详;handleBindApplication()方法之后个扰,流程會(huì)繼續(xù)在主線(xiàn)程中運(yùn)行,回到ActivityManagerService中的attachApplicationLocked()方法中葱色,往下調(diào)用ATMS中的attachApplication()方法递宅,之后會(huì)繼續(xù)調(diào)用到ActivityStackSupervisor中的realStartActivityLocked()方法來(lái)啟動(dòng)Activity;
- ActivityStackSupervisor中的realStartActivityLocked()方法在 Activity 的啟動(dòng)過(guò)程中處理 Activity 的創(chuàng)建苍狰、生命周期的管理办龄,處理與任務(wù)和堆棧相關(guān)的邏輯,進(jìn)行必要的配置檢查淋昭,確保 Activity 能夠正確無(wú)誤地啟動(dòng)俐填,其中創(chuàng)建了Activity啟動(dòng)事務(wù)ClientTransaction,用來(lái)處理Activity啟動(dòng)翔忽、停止和銷(xiāo)毀等事務(wù)的類(lèi)英融,ClientTransaction的CallBack中傳入了LaunchActivityItem;
- 應(yīng)用程序收到Activity啟動(dòng)事務(wù)ClientTransaction的方法回調(diào)后會(huì)走到ActivityThread中的ApplicationThread 類(lèi)處理應(yīng)用的生命周期事件歇式,在UI線(xiàn)程上協(xié)調(diào)操作驶悟,以及參與應(yīng)用的啟動(dòng)過(guò)程, scheduleTransaction接收到回調(diào)之后材失,會(huì)把消息給到ActivityThread的H處理痕鳍,而H會(huì)把ClientTransaction這個(gè)消息給到TransactionExecutor中的executeCallbacks ()方法處理;
- TransactionExecutor中的executeCallbacks()方法的作用是執(zhí)行所有掛起的回調(diào)(Callbacks)龙巨,遍歷 mPendingActions包含所有待執(zhí)行的操作(如 onPause()笼呆、onResume() 等)的列表,executeCallbacks 方法會(huì)依次執(zhí)行這些操作恭应,并從列表中移除已執(zhí)行的操作抄邀。
- ActivityStackSupervisor中的realStartActivityLocked()方法中創(chuàng)建的Activity啟動(dòng)事務(wù)ClientTransaction的CallBack參數(shù)中傳入了LaunchActivityItem,LaunchActivityItem作為啟動(dòng)Activity的消息對(duì)象發(fā)送到目標(biāo)對(duì)應(yīng)的ActivityThread中昼榛,通過(guò)調(diào)用 LaunchActivityItem 中的 execute() 方法來(lái)實(shí)際啟動(dòng) Activity境肾,而execute()主要是通過(guò)調(diào)用ActivityThread中的handleLaunchActivity()方法來(lái)處理Activity的啟動(dòng);
- ActivityThread中的handleLaunchActivity()方法的作用是處理啟動(dòng)Activity的操作胆屿,做一些調(diào)用其生命周期方法以及處理布局和顯示的操作奥喻,Activity實(shí)際的啟動(dòng)操作會(huì)調(diào)用ActivityThread中的performLaunchActivity方法執(zhí)行;
- ActivityThread中的performLaunchActivity方法通過(guò)ActivityClientRecord 對(duì)象獲取目標(biāo)Activity的信息非迹,通過(guò)反射機(jī)制創(chuàng)建Activity實(shí)例环鲤,然后做一些準(zhǔn)備Activity的上下文、初始化Activty憎兽、調(diào)用Activity生命周期等操作,最后將創(chuàng)建好的Activity實(shí)例返回顯示。