Android應(yīng)用啟動(dòng)流程

本文基于Android10
參考:Activity啟動(dòng)流程

Launcher進(jìn)程請(qǐng)求ATMS(AMS)

image

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淳玩。

  1. ATMS(AMS)做為服務(wù)端的服務(wù),存在于SystemServer進(jìn)程中非竿。

其實(shí)現(xiàn)了IActivityTaskManager.Stub(IActivityManager.Stub)蜕着,是個(gè)系統(tǒng)服務(wù)。

  1. 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ì)有所差異

image

這幾個(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

這里面主要做了幾件事情:

  1. 啟動(dòng)模式處理

  2. 創(chuàng)建ActivityRecord

  3. .....,

  4. 冷啟動(dòng)取activity的主題背景握牧,展示StartingWindow(冷啟動(dòng)白屏的原因,在發(fā)起fork進(jìn)程前就顯示主題)

  5. 通過(guò)IApplicationThread是否為null來(lái)判斷應(yīng)用進(jìn)程是否已經(jīng)存在娩梨,有則表示進(jìn)程已經(jīng)存在

IApplicationThread是應(yīng)用進(jìn)程在系統(tǒng)進(jìn)程的代理

  1. 如果進(jìn)程不存在沿腰,通過(guò)AMS發(fā)起創(chuàng)建進(jìn)程的請(qǐng)求
  2. 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)程

image

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í)例拷貝浪规。

  1. 啟動(dòng)SystemServer進(jìn)程,其main方法創(chuàng)建了應(yīng)用所需的各種服務(wù)探孝,如AMS笋婿,WMS等

  2. 調(diào)用ZygoteServer.runSelectLoop死循環(huán),用于等待AMS請(qǐng)求

  3. 當(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

image
  1. 當(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方法

  1. 通過(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

image
  1. 創(chuàng)建主線程Looper并開(kāi)啟循環(huán)

  2. 將ApplicationThread綁定到AMS滔驶,使AMS持有當(dāng)前進(jìn)程的ApplicationThread代理

  3. 創(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)求

image

流程:

-> 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

  1. 由上可知产徊,在AMS綁定ApplicationThread之后,調(diào)用mAtmInternal(實(shí)現(xiàn)類(lèi)LocalService)綁定Application

  2. 經(jīng)過(guò)一些列類(lèi)與方法的調(diào)用最終通過(guò)AMS調(diào)用應(yīng)用進(jìn)程的ApplicationThread代理創(chuàng)建事務(wù)

  3. ApplicationThread通過(guò)ActivityThread的Handler發(fā)送消息到主線程創(chuàng)建Activity

  4. ActivityThread執(zhí)行handleLaunchActivity蜀细,進(jìn)行Activity舟铜、Window的創(chuàng)建流程

Window的創(chuàng)建流程

  1. ActivityThread執(zhí)行handleStartActivity
  2. 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é)

  1. Zygote進(jìn)程啟動(dòng)時(shí)迫横,首先f(wàn)ork一個(gè)SystemServer進(jìn)程鸦难,SystemServer進(jìn)程創(chuàng)建了如AMS、WMS等系統(tǒng)服務(wù)

  2. Zygote進(jìn)程员淫,開(kāi)啟一個(gè)循環(huán)合蔽,用于等待AMS的請(qǐng)求

  3. Launcher做為一個(gè)Activity,發(fā)起創(chuàng)建Activity的請(qǐng)求介返,添加Flag為Intent.FLAG_ACTIVITY_NEW_TASK

  4. Instrementation獲取到ATMS(android10之前為AMS)拴事,發(fā)送啟動(dòng)Activity的請(qǐng)求

  5. 如果是冷啟動(dòng)沃斤,ATMS(AMS)向Zygote發(fā)起創(chuàng)建進(jìn)程的請(qǐng)求

并取activity的主題背景,用于展示StartingWindow(白屏原因

  1. Zygote收到請(qǐng)求后刃宵,fork一個(gè)進(jìn)程衡瓶,通過(guò)反射調(diào)用ActivityThread的main方法進(jìn)行初始化

  2. ActivityThread創(chuàng)建一個(gè)當(dāng)前進(jìn)程的ApplicationThread的,并將其綁定到AMS

  3. AMS收到ApplicationThread的代理后牲证,調(diào)用ApplicationThread進(jìn)行Applicaition的初始化

  4. Application通過(guò)Handle發(fā)送消息到主線程哮针,ActivityThread收到消息后,創(chuàng)建Application坦袍,并執(zhí)行attach十厢、onCreate等方法

  5. AMS調(diào)用ApplicationThread開(kāi)啟創(chuàng)建Activity的事務(wù)

  6. Application通過(guò)Handle發(fā)送消息到主線程,ActivityThread收到消息后捂齐,進(jìn)行Activity的啟動(dòng)

  7. ActivityThread執(zhí)行handleLaunchActivity蛮放,進(jìn)行Activity、Window的創(chuàng)建流程

Window的創(chuàng)建流程

  1. ActivityThread執(zhí)行handleStartActivity
  2. 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)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末嘴高,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子和屎,更是在濱河造成了極大的恐慌拴驮,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,214評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件柴信,死亡現(xiàn)場(chǎng)離奇詭異套啤,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)随常,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,307評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門(mén)潜沦,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人绪氛,你說(shuō)我怎么就攤上這事唆鸡。” “怎么了枣察?”我有些...
    開(kāi)封第一講書(shū)人閱讀 152,543評(píng)論 0 341
  • 文/不壞的土叔 我叫張陵争占,是天一觀的道長(zhǎng)燃逻。 經(jīng)常有香客問(wèn)我,道長(zhǎng)臂痕,這世上最難降的妖魔是什么伯襟? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 55,221評(píng)論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮握童,結(jié)果婚禮上姆怪,老公的妹妹穿的比我還像新娘。我一直安慰自己澡绩,他們只是感情好稽揭,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,224評(píng)論 5 371
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著英古,像睡著了一般淀衣。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上召调,一...
    開(kāi)封第一講書(shū)人閱讀 49,007評(píng)論 1 284
  • 那天膨桥,我揣著相機(jī)與錄音,去河邊找鬼唠叛。 笑死只嚣,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的艺沼。 我是一名探鬼主播册舞,決...
    沈念sama閱讀 38,313評(píng)論 3 399
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼障般!你這毒婦竟也來(lái)了调鲸?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 36,956評(píng)論 0 259
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤挽荡,失蹤者是張志新(化名)和其女友劉穎藐石,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體定拟,經(jīng)...
    沈念sama閱讀 43,441評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡于微,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,925評(píng)論 2 323
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了青自。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片株依。...
    茶點(diǎn)故事閱讀 38,018評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖延窜,靈堂內(nèi)的尸體忽然破棺而出恋腕,到底是詐尸還是另有隱情,我是刑警寧澤逆瑞,帶...
    沈念sama閱讀 33,685評(píng)論 4 322
  • 正文 年R本政府宣布吗坚,位于F島的核電站祈远,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏商源。R本人自食惡果不足惜车份,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,234評(píng)論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望牡彻。 院中可真熱鬧扫沼,春花似錦、人聲如沸庄吼。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,240評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)总寻。三九已至器罐,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間渐行,已是汗流浹背轰坊。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,464評(píng)論 1 261
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留祟印,地道東北人肴沫。 一個(gè)月前我還...
    沈念sama閱讀 45,467評(píng)論 2 352
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像蕴忆,于是被迫代替她去往敵國(guó)和親颤芬。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,762評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容