本文基于Android10
參考:Activity啟動(dòng)流程
Launcher進(jìn)程請(qǐng)求ATMS(AMS)
Launcher
請(qǐng)求的入口為L(zhǎng)auncher的startActivitySafe方法
調(diào)用父類(lèi)的startActivity方法
// Launcher是一個(gè)Activity
public class Launcher extends BaseDraggingActivity implements LauncherExterns,
LauncherModel.Callbacks, LauncherProviderChangeListener, UserEventDelegate{
public boolean startActivitySafely(View v, Intent intent, ItemInfo item) {
...
// 在新的任務(wù)棧中啟動(dòng)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
...
if (isShortcut) {
// Shortcuts need some special checks due to legacy reasons.
startShortcutIntentSafely(intent, optsBundle, item);
} else if (user == null || user.equals(Process.myUserHandle())) {
// 調(diào)用startActivity
startActivity(intent, optsBundle);
} else {
LauncherAppsCompat.getInstance(this).startActivityForProfile(
intent.getComponent(), user, intent.getSourceBounds(), optsBundle);
}
...
return true;
} catch (ActivityNotFoundException|SecurityException e) {
...
}
return false;
}
}
Activity
通過(guò)Instrumentation啟動(dòng)Activity
public class Activity extends ...{
// startActivity最終都會(huì)走到這里
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
@Nullable Bundle options) {
// mParent表示當(dāng)前Activity的父類(lèi)今妄,當(dāng)根活動(dòng)還沒(méi)創(chuàng)建則mParent==null
if (mParent == null) {
options = transferSpringboardActivityOptions(options);
// 通過(guò)Instrumentation啟動(dòng)Activity
// 比較重要的幾個(gè)參數(shù):ApplicationThread(Binder)惩歉、Token
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);
...
}
...
}
}
Instrumentation
Instrumentation具有跟蹤application及activity生命周期的功能碴裙,用于android 應(yīng)用測(cè)試框架中代碼檢測(cè)
每個(gè)Activity都持有Instrumentation對(duì)象的一個(gè)引用灯谣,但是整個(gè)進(jìn)程只會(huì)存在一個(gè)Instrumentation對(duì)象
public class Instrumentation {
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
...
try {
...
// 獲取ActivityTaskManagerService(ATMS),是個(gè)跨進(jìn)程Binder服務(wù)
// ATMS 是Android10新增的忿薇,在此之前甜癞,這里獲取的是AMS
// whoThread為ApplicationThread
int result = ActivityTaskManager.getService()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target != null ? target.mEmbeddedID : null,
requestCode, 0, null, options);
// 檢查Activity啟動(dòng)的結(jié)果苟穆,如果異常則拋出錯(cuò)誤妓忍,如Activity沒(méi)有注冊(cè)的錯(cuò)誤等
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
}
return null;
}
}
ActivityTaskManager(ATMS甲喝、AMS)
Android10新增尝苇,Android10之前,調(diào)用的是AMS。
Android10的AMS內(nèi)部糠溜,也是調(diào)用ATMS淳玩。
- ATMS(AMS)做為服務(wù)端的服務(wù),存在于SystemServer進(jìn)程中非竿。
其實(shí)現(xiàn)了IActivityTaskManager.Stub(IActivityManager.Stub)蜕着,是個(gè)系統(tǒng)服務(wù)。
- Launcher做為客戶端進(jìn)程红柱,通過(guò)IActivityTaskManager.Stub.asInterface拿到了服務(wù)端ATMS的代理對(duì)象承匣,可以跨進(jìn)程調(diào)用ATMS(AMS)的方法來(lái)實(shí)現(xiàn)具體功能
// ActivityTaskManager
public static IActivityTaskManager getService() {
return IActivityTaskManagerSingleton.get();
}
private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton =
new Singleton<IActivityTaskManager>() {
@Override
protected IActivityTaskManager create() {
// 獲取ATMS,是個(gè)Binder服務(wù)
final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);
return IActivityTaskManager.Stub.asInterface(b);
}
};
ATMS(AMS)發(fā)送創(chuàng)建應(yīng)用進(jìn)程請(qǐng)求
ActivityTaskManagerService.startActivity 整個(gè)流程圖如下:
圖是android10之前的锤悄,跟本文會(huì)有所差異
這幾個(gè)類(lèi)跳來(lái)跳去韧骗,有點(diǎn)懵逼,就不貼代碼了零聚,可以自己去點(diǎn)看看宽闲,不同Android版本會(huì)有差異。
調(diào)用路徑:
-> ActivityTaskManager#startActivity
-> ActivityTaskManager#startActivityAsUser
-> ActivityStarter#execute
-> ActivityStarter#startActivity
-> ActivityStarter#startActivityUnchecked
-> RootActivityContainer#resumeFocusedStacksTopActivities
-> ActivityStack#resumeTopActivityUncheckedLocked
-> ActivityStack#resumeTopActivityInnerLocked
-> ActivityStackSupervisor#startSpecificActivityLocked
這里面主要做了幾件事情:
啟動(dòng)模式處理
創(chuàng)建ActivityRecord
.....,
冷啟動(dòng)取activity的主題背景握牧,展示StartingWindow(冷啟動(dòng)白屏的原因,在發(fā)起fork進(jìn)程前就顯示主題)
通過(guò)IApplicationThread是否為null來(lái)判斷應(yīng)用進(jìn)程是否已經(jīng)存在娩梨,有則表示進(jìn)程已經(jīng)存在
IApplicationThread是應(yīng)用進(jìn)程在系統(tǒng)進(jìn)程的代理
- 如果進(jìn)程不存在沿腰,通過(guò)AMS發(fā)起創(chuàng)建進(jìn)程的請(qǐng)求
- AMS通過(guò)Process向Zygote進(jìn)程發(fā)送創(chuàng)建應(yīng)用進(jìn)程請(qǐng)求
// ActivityStack#resumeTopActivityInnerLocked
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
...
// pause一個(gè)Activity
startPausingLocked(userLeaving, false, next, false);
...
// 如果activity已經(jīng)啟動(dòng)
if (next.attachedToProcess()) {
...
//啟動(dòng)了的Activity就發(fā)送ResumeActivityItem事務(wù)給客戶端了,后面會(huì)講到
transaction.setLifecycleStateRequest(
ResumeActivityItem.obtain(next.app.getReportedProcState(),
getDisplay().mDisplayContent.isNextTransitionForward()));
mService.getLifecycleManager().scheduleTransaction(transaction);
....
} else {
....
if (SHOW_APP_STARTING_PREVIEW) {
// 冷啟動(dòng)時(shí)出現(xiàn)白屏的原因:取根activity的主題背景狈定,展示StartingWindow
next.showStartingWindow(null, false ,false);
}
mStackSupervisor.startSpecificActivityLocked(next, true, true);
}
return true;
}
判斷進(jìn)程是否已存在
// ActivityStackSupervisor#startSpecificActivityLocked
void startSpecificActivityLocked(ActivityRecord r,
boolean andResume, boolean checkConfig) {
// 通過(guò)進(jìn)程名及uid獲取即將啟動(dòng)的進(jìn)程
final WindowProcessController wpc =
mService.getProcessController(r.processName, r.info.applicationInfo.uid);
// 如果應(yīng)用進(jìn)程已經(jīng)存在颂龙,內(nèi)部通過(guò)IApplicationThread是否為null來(lái)判斷
if (wpc != null && wpc.hasThread()) {
// Activity熱啟動(dòng)
realStartActivityLocked(r, wpc, andResume, checkConfig);
return;
}
...
// 否則,創(chuàng)建進(jìn)程
// ActivityManagerInternal::startProcess 調(diào)用ActivityManagerService(AMS)
final Message msg = PooledLambda.obtainMessage(
ActivityManagerInternal::startProcess, mService.mAmInternal, r.processName,
r.info.applicationInfo, knownToBeDead, "activity", r.intent.getComponent());
mService.mH.sendMessage(msg);
}
Process向Zygote發(fā)送創(chuàng)建進(jìn)程的請(qǐng)求
private Process.ProcessStartResult startProcess(HostingRecord hostingRecord, String entryPoint,
ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
String seInfo, String requiredAbi, String instructionSet, String invokeWith,
long startTime) {
...
startResult = Process.start(entryPoint,
app.processName, uid, uid, gids, runtimeFlags, mountExternal,
app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
app.info.dataDir, invokeWith, app.info.packageName,
new String[] {PROC_START_SEQ_IDENT + app.startSeq});
}
checkSlow(startTime, "startProcess: returned from zygote!");
return startResult;
}
// Process#start
public static ProcessStartResult start(@NonNull final String processClass,
@Nullable final String niceName,
int uid, int gid, @Nullable int[] gids,
int runtimeFlags,
int mountExternal,
int targetSdkVersion,
@Nullable String seInfo,
@NonNull String abi,
@Nullable String instructionSet,
@Nullable String appDataDir,
@Nullable String invokeWith,
@Nullable String packageName,
@Nullable String[] zygoteArgs) {
// 與Zygote進(jìn)程建立了Socket連接纽什,并發(fā)送創(chuàng)建進(jìn)程請(qǐng)求
return ZYGOTE_PROCESS.start(processClass, niceName, uid, gid, gids,
runtimeFlags, mountExternal, targetSdkVersion, seInfo,
abi, instructionSet, appDataDir, invokeWith, packageName,
/*useUsapPool=*/ true, zygoteArgs);
}
Zygote進(jìn)程接受請(qǐng)求并fork應(yīng)用進(jìn)程
Zygote:在Android系統(tǒng)中措嵌,DVM(Dalvik虛擬機(jī))、應(yīng)用程序進(jìn)程以及運(yùn)行系統(tǒng)的關(guān)鍵服務(wù)的SystemServer進(jìn)程都是由Zygote進(jìn)程來(lái)創(chuàng)建的芦缰,我們也將它稱(chēng)為孵化器企巢。它通過(guò)fork(復(fù)制進(jìn)程)的形式來(lái)創(chuàng)建應(yīng)用程序進(jìn)程和SystemServer進(jìn)程,由于Zygote進(jìn)程在啟動(dòng)時(shí)會(huì)創(chuàng)建DVM让蕾,因此通過(guò)fork而創(chuàng)建的應(yīng)用程序進(jìn)程和SystemServer進(jìn)程可以在內(nèi)部獲取一個(gè)DVM的實(shí)例拷貝浪规。
啟動(dòng)SystemServer進(jìn)程,其main方法創(chuàng)建了應(yīng)用所需的各種服務(wù)探孝,如AMS笋婿,WMS等
調(diào)用ZygoteServer.runSelectLoop死循環(huán),用于等待AMS請(qǐng)求
當(dāng)收到AMS請(qǐng)求顿颅,會(huì)fork一個(gè)應(yīng)用進(jìn)程
等待AMS請(qǐng)求
// ZygoteInit#main
public static void main(String argv[]) {
// 創(chuàng)建Socket
ZygoteServer zygoteServer = new ZygoteServer();
....
// 啟動(dòng)SystemServer, 可見(jiàn)SystemServer是由Zygote創(chuàng)建的第一個(gè)進(jìn)程
forkSystemServer(abiList, zygoteSocketName, zygoteServer)
...
// 等待客戶端(AMS)請(qǐng)求
zygoteServer.runSelectLoop(abiList);
...
}
Runnable runSelectLoop(String abiList) {
...
while (true) {
...
// 不斷處理客戶端的AMS的請(qǐng)求缸濒,然后交給processOneCommand
ZygoteConnection connection = peers.get(pollIndex);
final Runnable command = connection.processOneCommand(this);
...
}
}
Zygote fork 子進(jìn)程(應(yīng)用進(jìn)程)
// ZygoteConnect#processOneCommand
Runnable processOneCommand(ZygoteServer zygoteServer) {
....
// fork當(dāng)前進(jìn)程創(chuàng)建一個(gè)子進(jìn)程
int pid = Zygote.forkAndSpecialize(一堆啟動(dòng)參數(shù));
// pid為0則表示當(dāng)前進(jìn)程已經(jīng)是子進(jìn)程了,即應(yīng)用進(jìn)程
if (pid == 0) {
...
//
return handleChildProc(parsedArgs, descriptors, childPipeFd,
parsedArgs.mStartChildZygote);
}
...
}
啟動(dòng)ActivityThread
- 當(dāng)zygote fork一個(gè)進(jìn)程后返回一個(gè)pid
當(dāng)pid=0的時(shí),則代表了當(dāng)前進(jìn)程已經(jīng)是子進(jìn)程了庇配,即應(yīng)用進(jìn)程斩跌。所下一步將執(zhí)行handleChildProc方法
- 通過(guò)反射調(diào)用ActivityThread 的main方法完成初始化
// ZygoteConnect#handleChildProc
private Runnable handleChildProc(ZygoteArguments parsedArgs, FileDescriptor[] descriptors,
FileDescriptor pipeFd, boolean isZygote) {
.....
ZygoteInit.zygoteInit(參數(shù));
...
}
// ZygoteInit#zygoteInit
public static final Runnable zygoteInit(int targetSdkVersion, String[] argv,
ClassLoader classLoader) {
// 為當(dāng)前的VM設(shè)置未捕獲異常器
RuntimeInit.commonInit();
// Binder驅(qū)動(dòng)初始化,該方法完成后讨永,可通過(guò)Binder進(jìn)行進(jìn)程通信
ZygoteInit.nativeZygoteInit();
// 主要調(diào)用SystemServer的main方法
return RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader);
}
// RuntimeInit#applicationInit
protected static Runnable applicationInit(int targetSdkVersion, String[] argv,
ClassLoader classLoader) {
...
final Arguments args = new Arguments(argv);
// 這里的startClass為ActivityThread, 找到它的main方法并反射調(diào)用
return findStaticMain(args.startClass, args.startArgs, classLoader);
}
// RuntimeInit#findStaticMain
protected static Runnable findStaticMain(String className, String[] argv,
ClassLoader classLoader) {
// className為ActivityThread
// 反射獲取到ActivityThread類(lèi)并調(diào)用main方法
Class<?> cl = Class.forName(className, true, classLoader);
Method m = cl.getMethod("main", new Class[] { String[].class });
return new MethodAndArgsCaller(m, argv);
}
應(yīng)用進(jìn)程綁定到AMS
創(chuàng)建主線程Looper并開(kāi)啟循環(huán)
將ApplicationThread綁定到AMS滔驶,使AMS持有當(dāng)前進(jìn)程的ApplicationThread代理
創(chuàng)建Applicaiton,并調(diào)用onCreate
public final class ActivityThread extends ClientTransactionHandler {
// ActivityThread的內(nèi)部類(lèi)卿闹,實(shí)現(xiàn)IApplicationThread.Stub揭糕,負(fù)責(zé)與AMS通訊
final ApplicationThread mAppThread = new ApplicationThread();
// ActivityThread#main
public static void main(String[] args) {
....
// 創(chuàng)建主線程的Looper
Looper.prepareMainLooper();
...
// 創(chuàng)建ActivityThread
ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);
// 開(kāi)啟主線程的消息循環(huán)
Looper.loop();
...
}
private void attach(boolean system, long startSeq) {
...
// 獲取 AMS 服務(wù)
final IActivityManager mgr = ActivityManager.getService();
// ApplicationThread 綁定到AMS,這是一個(gè)IPC過(guò)程
mgr.attachApplication(mAppThread, startSeq);
}
// 應(yīng)用創(chuàng)建Application
private void handleBindApplication(AppBindData data) {
....
// 創(chuàng)建Application
Application app = data.info.makeApplication(data.restrictedBackupMode, null);
// 調(diào)用Application的onCreate的方法
// 此時(shí)的Activity還沒(méi)啟動(dòng)
mInstrumentation.callApplicationOnCreate(app);
...
}
class H extends Handler {
public static final int BIND_APPLICATION = 110;
...
public void handleMessage(Message msg) {
switch (msg.what) {
case BIND_APPLICATION:
AppBindData data = (AppBindData)msg.obj;
handleBindApplication(data);
break;
...
}
}
private class ApplicationThread extends IApplicationThread.Stub {
public final void bindApplication(一堆參數(shù)) {
...
AppBindData data = new AppBindData();
...
// AMS綁定ApplicationThread時(shí)锻霎,發(fā)送消息到ActivityThread創(chuàng)建Application
sendMessage(H.BIND_APPLICATION, data);
}
}
}
// ActivityManagerService
private final boolean attachApplicationLocked(IApplicationThread thread,
int pid, int callingUid, long startSeq) {
ProcessRecord app;
....
// AMS 調(diào)用ApplicationThread, 創(chuàng)建Applicaition著角,回調(diào)onCreate
thread.bindApplication(一堆參數(shù));
...
// 將 applicationThread 設(shè)置到 ProcessRecord
// 所以啟動(dòng)activity時(shí),能夠拿到當(dāng)前進(jìn)程的 applicationThrea, 由此判斷進(jìn)程是否已經(jīng)存在
app.makeActive(thread, mProcessStats);
...
// 啟動(dòng)Activity
// mAtmInternal實(shí)現(xiàn)類(lèi)為ATMS的內(nèi)部類(lèi) LocalService
mAtmInternal.attachApplication(app.getWindowProcessController());
.....
}
AMS發(fā)送啟動(dòng)Activity的請(qǐng)求
流程:
-> ActivityTaskManagerService.LocalService#attachApplication
-> RootActivityContiner#attachApplication
-> ActivityStackSupervisor#realStartActivityLocked
(熱啟動(dòng)旋恼,ActivityStackSupervisor#startSpecificActivityLocked判斷如果是熱啟動(dòng)吏口,走這里的流程)
-> ClientLifecycleManager#scheduleTransaction
-> ClientTransaction#schedule
-> IApplicationThread#scheduleTransaction
-> ActivityThread#scheduleTransaction(這里調(diào)用的是父類(lèi)ClientTransactionHandler的方法)
-> Handle發(fā)送ActivityThread.H.EXECUTE_TRANSACTION 消息
-> TransactionExecutor#execute (Handle收到消息后)
-> TransactionExecutor#executeCallbacks
-> LaunchActivityItem#execute
-> ActivityThread#handleLaunchActivity
-> 創(chuàng)建Activity、Window冰更、DecorView
-> ActivityThread#handleStartActivity
-> ResumeActivityItem#execute
-> ActivityThread#handleResumeActivity
由上可知产徊,在AMS綁定ApplicationThread之后,調(diào)用mAtmInternal(實(shí)現(xiàn)類(lèi)LocalService)綁定Application
經(jīng)過(guò)一些列類(lèi)與方法的調(diào)用最終通過(guò)AMS調(diào)用應(yīng)用進(jìn)程的ApplicationThread代理創(chuàng)建事務(wù)
ApplicationThread通過(guò)ActivityThread的Handler發(fā)送消息到主線程創(chuàng)建Activity
ActivityThread執(zhí)行handleLaunchActivity蜀细,進(jìn)行Activity舟铜、Window的創(chuàng)建流程
- ActivityThread執(zhí)行handleStartActivity
- ActivityThread執(zhí)行handleResumeActivity,通過(guò)WMS進(jìn)行window的添加
// ActivityStackSupervisor#realStartActivityLocked
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
boolean andResume, boolean checkConfig) throws RemoteException {
.....
final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
r.appToken);
// 添加callback
// 創(chuàng)建LaunchActivityItem
clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),...));
// ResumeActivityItem
final ActivityLifecycleItem lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
// 設(shè)置當(dāng)前的生命周期
clientTransaction.setLifecycleStateRequest(lifecycleItem);
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
....
return true;
}
// TransactionExecutor#execute
public void execute(ClientTransaction transaction) {
...
// 其實(shí)就是執(zhí)行LaunchActivityItem奠衔,回調(diào)onCreate
executeCallbacks(transaction);
// 其實(shí)就是執(zhí)行ResumeActivityItem谆刨,回調(diào)onStart、onCreate
executeLifecycleState(transaction);
}
// TransactionExecutor#executeCallbacks
// 執(zhí)行LaunchActivityItem
public void executeCallbacks(ClientTransaction transaction) {
final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
......
final int size = callbacks.size();
for (int i = 0; i < size; ++i) {
// 這里的item為L(zhǎng)aunchActivityItem
final ClientTransactionItem item = callbacks.get(i);
......
item.execute(mTransactionHandler, token, mPendingActions);
item.postExecute(mTransactionHandler, token, mPendingActions);
......
}
}
// LaunchActivityItem#execute
@Override
public void execute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
// 創(chuàng)建ActivityClientRecord
ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
mPendingResults, mPendingNewIntents, mIsForward,
mProfilerInfo, client);
// 這里的client為ActivityThread
client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
}
// ActivityThread#handleLaunchActivity
public Activity handleLaunchActivity(ActivityClientRecord r,
PendingTransactionActions pendingActions, Intent customIntent) {
// 反射創(chuàng)建Activity归斤,執(zhí)行Activity.attach創(chuàng)建window痊夭,然后回掉onCreate
final Activity a = performLaunchActivity(r, customIntent);
return a;
}
// TransactionExecutor#executeLifecycleState
// 執(zhí)行ResumeActivityItem
private void executeLifecycleState(ClientTransaction transaction) {
final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
....
// 執(zhí)行當(dāng)前生命周期狀態(tài)之前的狀態(tài),當(dāng)前為onResume脏里,所以這里執(zhí)行的是onStart她我,調(diào)用ActivityThread#handleStartActivity
cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */);
// 切換狀態(tài)到onResume,調(diào)用ActivityThread#handleResumeActivity
lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
}
總結(jié)
Zygote進(jìn)程啟動(dòng)時(shí)迫横,首先f(wàn)ork一個(gè)SystemServer進(jìn)程鸦难,SystemServer進(jìn)程創(chuàng)建了如AMS、WMS等系統(tǒng)服務(wù)
Zygote進(jìn)程员淫,開(kāi)啟一個(gè)循環(huán)合蔽,用于等待AMS的請(qǐng)求
Launcher做為一個(gè)Activity,發(fā)起創(chuàng)建Activity的請(qǐng)求介返,添加Flag為Intent.FLAG_ACTIVITY_NEW_TASK
Instrementation獲取到ATMS(android10之前為AMS)拴事,發(fā)送啟動(dòng)Activity的請(qǐng)求
如果是冷啟動(dòng)沃斤,ATMS(AMS)向Zygote發(fā)起創(chuàng)建進(jìn)程的請(qǐng)求
并取activity的主題背景,用于展示StartingWindow(白屏原因)
Zygote收到請(qǐng)求后刃宵,fork一個(gè)進(jìn)程衡瓶,通過(guò)反射調(diào)用ActivityThread的main方法進(jìn)行初始化
ActivityThread創(chuàng)建一個(gè)當(dāng)前進(jìn)程的ApplicationThread的,并將其綁定到AMS
AMS收到ApplicationThread的代理后牲证,調(diào)用ApplicationThread進(jìn)行Applicaition的初始化
Application通過(guò)Handle發(fā)送消息到主線程哮针,ActivityThread收到消息后,創(chuàng)建Application坦袍,并執(zhí)行attach十厢、onCreate等方法
AMS調(diào)用ApplicationThread開(kāi)啟創(chuàng)建Activity的事務(wù)
Application通過(guò)Handle發(fā)送消息到主線程,ActivityThread收到消息后捂齐,進(jìn)行Activity的啟動(dòng)
ActivityThread執(zhí)行handleLaunchActivity蛮放,進(jìn)行Activity、Window的創(chuàng)建流程
- ActivityThread執(zhí)行handleStartActivity
- ActivityThread執(zhí)行handleResumeActivity奠宜,通過(guò)WMS進(jìn)行window的添加
PS:
- 如果是熱啟動(dòng)包颁,AMS持有了當(dāng)前進(jìn)程的ApplicationThread代理,所以步驟4之后會(huì)直接走步驟10的流程
- 由于冷啟動(dòng)压真,會(huì)先在主線程創(chuàng)建Application并執(zhí)行生命周期方法娩嚼,所以如果在Application執(zhí)行耗時(shí)方法,會(huì)導(dǎo)致Activity的啟動(dòng)被阻塞滴肿,所以Application如果有耗時(shí)操作需要放在異步線程中執(zhí)行岳悟。
到此,就完成了Activity的啟動(dòng)