Activity启动流程

简述

Activity 启动分为两种:
1、Activity中通过startActivity()方法启动一个Activity
2、从桌面通过点击应用图标启动一个App然后显示Activity


我们通过第二点来分析,更全面一点
先走一波流程图:

Activity 启动流程图

以下源码基于Android 10 (android-29)


一、Launcher向AMS发送启动Activity

Launcher本身是一个Activity,在用户点击应用图标时,调用startActivitySafely方法,最后调用到Activity.startActivity(),函数调用如下

Launcher.java
 public boolean startActivitySafely(View v, Intent intent, ItemInfo item) {
  ...
  //标记在新的栈启动
  intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  ...
  startActivity(intent, optsBundle);
  ...
 }

在Activity中继续调用

// Activity.java
   @Override
    public void startActivity(Intent intent) {
        this.startActivity(intent, null);
    }

    @Override
    public void startActivity(Intent intent, @Nullable Bundle options) {
        if (options != null) {
            startActivityForResult(intent, -1, options);
        } else {
            // Note we want to go through this call for compatibility with
            // applications that may have overridden the method.
            startActivityForResult(intent, -1);
        }
    }

    public void startActivityForResult(@RequiresPermission Intent intent, int requestCode) {
        startActivityForResult(intent, requestCode, null);
    }

    public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
            @Nullable Bundle options) {
        if (mParent == null) {
           ...
             // 注重点 1️⃣
            Instrumentation.ActivityResult ar =
                mInstrumentation.execStartActivity(
                    this, mMainThread.getApplicationThread(), mToken, this,
                    intent, requestCode, options);
            ...
        } else {
            if (options != null) {
                mParent.startActivityFromChild(this, intent, requestCode, options);
            } else {
                // Note we want to go through this method for compatibility with
                // existing applications that may have overridden it.
                mParent.startActivityFromChild(this, intent, requestCode);
            }
        }
    }

    public void startActivityFromChild(@NonNull Activity child, @RequiresPermission Intent intent,
            int requestCode) {
        startActivityFromChild(child, intent, requestCode, null);
    }
    public void startActivityFromChild(@NonNull Activity child, @RequiresPermission Intent intent,
            int requestCode, @Nullable Bundle options) {
        options = transferSpringboardActivityOptions(options);
        // 注重点 2️⃣
        Instrumentation.ActivityResult ar =
            mInstrumentation.execStartActivity(
                this, mMainThread.getApplicationThread(), mToken, child,
                intent, requestCode, options);
       ...
    }

每个Activity都持有Instrumentation对象,1️⃣和2️⃣都是通过它的execStartActivity方法来启动Activity的,这个函数中传入了mMainThread.getApplicationThread(),它获取到的是ActivityThread的内部类ApplicationThread,这是一个Binder对象,之后AMS通过此对象与App的通信。


// Instrumentation.java
    @UnsupportedAppUsage
    public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {
       ...
        try {
          ...
            // 重点1️⃣
            int result = ActivityTaskManager.getService()
                .startActivity(whoThread, who.getBasePackageName(), intent,
                        intent.resolveTypeIfNeeded(who.getContentResolver()),
                        token, target != null ? target.mEmbeddedID : null,
                        requestCode, 0, null, options);
           ...
        } catch (RemoteException e) {
            throw new RuntimeException("Failure from system", e);
        }
        return null;
    }
// ActivityTaskManager.java
public static IActivityTaskManager getService() {
  return IActivityTaskManagerSingleton.get();
}
  
private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton =
   new Singleton<IActivityTaskManager>() {
    @Override
    protected IActivityTaskManager create() {
     final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);
     return IActivityTaskManager.Stub.asInterface(b);
    }
    }
};

这一步Launcher开始向ATMS通信,由于在不同的进程所以需要通过Binder来通信,IActivityTaskManager是一个代理ATMS端Binder的对象,之后ATMS开始startActivity。 到这里Launcher向ATMS请求启动一个Activity的流程就结束了。
注:新版本ATMS 接管AMS


二、AMS启动Activity并通知Launcher进入Paused状态

// ActivityTaskManagerService.java
public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
    @Override
    public final int startActivity(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
        return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
                resultWho, requestCode, startFlags, profilerInfo, bOptions,
                UserHandle.getCallingUserId());
    }

    @Override
    public int startActivityAsUser(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
        return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
                resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
                true /*validateIncomingUser*/);
    }

    int startActivityAsUser(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
            boolean validateIncomingUser) {
        enforceNotIsolatedCaller("startActivityAsUser");

        userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
                Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");

        // TODO: Switch to user app stacks here.
        // 重点1️⃣
        return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
                .setCaller(caller)
                .setCallingPackage(callingPackage)
                .setResolvedType(resolvedType)
                .setResultTo(resultTo)
                .setResultWho(resultWho)
                .setRequestCode(requestCode)
                .setStartFlags(startFlags)
                .setProfilerInfo(profilerInfo)
                .setActivityOptions(bOptions)
                .setMayWait(userId)
                .execute();

    }
}

此刻的ATMS是另外一个进程中,也就是说startActivity 通过Binder来启动ATMS


public class ActivityStartController {
  ...
    ActivityStarter obtainStarter(Intent intent, String reason) {
        return mFactory.obtain().setIntent(intent).setReason(reason);
    }
  ...
}
class ActivityStarter {
    /**
     * Starts an activity based on the request parameters provided earlier.
     * @return The starter result.
     */
    int execute() {
        try {
            // TODO(b/64750076): Look into passing request directly to these methods to allow
            // for transactional diffs and preprocessing.
            if (mRequest.mayWait) {
                return startActivityMayWait(mRequest.caller, mRequest.callingUid,
                        mRequest.callingPackage, mRequest.realCallingPid, mRequest.realCallingUid,
                        mRequest.intent, mRequest.resolvedType,
                        mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
                        mRequest.resultWho, mRequest.requestCode, mRequest.startFlags,
                        mRequest.profilerInfo, mRequest.waitResult, mRequest.globalConfig,
                        mRequest.activityOptions, mRequest.ignoreTargetSecurity, mRequest.userId,
                        mRequest.inTask, mRequest.reason,
                        mRequest.allowPendingRemoteAnimationRegistryLookup,
                        mRequest.originatingPendingIntent, mRequest.allowBackgroundActivityStart);
            } else {
                // 调用startActivity 1️⃣
                return startActivity(mRequest.caller, mRequest.intent, mRequest.ephemeralIntent,
                        mRequest.resolvedType, mRequest.activityInfo, mRequest.resolveInfo,
                        mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
                        mRequest.resultWho, mRequest.requestCode, mRequest.callingPid,
                        mRequest.callingUid, mRequest.callingPackage, mRequest.realCallingPid,
                        mRequest.realCallingUid, mRequest.startFlags, mRequest.activityOptions,
                        mRequest.ignoreTargetSecurity, mRequest.componentSpecified,
                        mRequest.outActivity, mRequest.inTask, mRequest.reason,
                        mRequest.allowPendingRemoteAnimationRegistryLookup,
                        mRequest.originatingPendingIntent, mRequest.allowBackgroundActivityStart);
            }
        } finally {
            onExecutionComplete();
        }
    }

     private int startActivityMayWait(IApplicationThread caller, int callingUid,
            String callingPackage, int requestRealCallingPid, int requestRealCallingUid,
            Intent intent, String resolvedType, IVoiceInteractionSession voiceSession,
            IVoiceInteractor voiceInteractor, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, WaitResult outResult,
            Configuration globalConfig, SafeActivityOptions options, boolean ignoreTargetSecurity,
            int userId, TaskRecord inTask, String reason,
            boolean allowPendingRemoteAnimationRegistryLookup,
            PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart) {
            ...
            final ActivityRecord[] outRecord = new ActivityRecord[1];
            // 调用startActivity 2️⃣
            int res = startActivity(caller, intent, ephemeralIntent, resolvedType, aInfo, rInfo,
                    voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid,
                    callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options,
                    ignoreTargetSecurity, componentSpecified, outRecord, inTask, reason,
                    allowPendingRemoteAnimationRegistryLookup, originatingPendingIntent,
                    allowBackgroundActivityStart);
            ...
  }
      //  1️⃣ 和 2️⃣调用startActivity
      private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
            String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
            String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
            SafeActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
            ActivityRecord[] outActivity, TaskRecord inTask, String reason,
            boolean allowPendingRemoteAnimationRegistryLookup,
            PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart) {
             ...
              // 调用startActivity 3️⃣
             mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,
                aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
                callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
                options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
                inTask, allowPendingRemoteAnimationRegistryLookup, originatingPendingIntent,
                allowBackgroundActivityStart);
             ...
    }

         //  3️⃣调用startActivity
        private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
            String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
            String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
            SafeActivityOptions options,
            boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity,
            TaskRecord inTask, boolean allowPendingRemoteAnimationRegistryLookup,
            PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart) {
            ....
            // 调用startActivity 4️⃣
            final int res = startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
                true /* doResume */, checkedOptions, inTask, outActivity, restrictedBgActivity);
            mSupervisor.getActivityMetricsLogger().notifyActivityLaunched(res, outActivity[0]);
           ....
    }
        
         //  4️⃣调用startActivity
        private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
                IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
                int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
                ActivityRecord[] outActivity, boolean restrictedBgActivity) {
                 ....
                // 调用startActivityUnchecked5️⃣
                result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
                    startFlags, doResume, options, inTask, outActivity, restrictedBgActivity);
                 ....
    }

     //  5️⃣调用startActivityUnchecked
        // Note: This method should only be called from {@link startActivity}.
    private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
            ActivityRecord[] outActivity, boolean restrictedBgActivity) {
        setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession,
                voiceInteractor, restrictedBgActivity);
          ...
          final int preferredWindowingMode = mLaunchParams.mWindowingMode;
          computeLaunchingTaskFlags(); // 6️⃣
          computeSourceStack(); // 7️⃣
          mIntent.setFlags(mLaunchFlags);
          ActivityRecord reusedActivity = getReusableIntentActivity();
          ...
          mRootActivityContainer.resumeFocusedStacksTopActivities(); // 8️⃣
          ...
    }
}   

标注6️⃣ :ActivityStarter.computeLaunchingTaskFlags() 方法是根据 Activity 的 launcher mode 和 intent.flag 计算出 Activity 的入栈方式。
标注7️⃣ :ActivityStarter.computeSourceStack() 计算从哪个栈中启动该 Activity。
标注8️⃣:调用了 RootActivityContainer.resumeFocusedStacksTopActivities 方法:


class RootActivityContainer extends ConfigurationContainer
        implements DisplayManager.DisplayListener {
        ...
        if (targetStack != null && (targetStack.isTopStackOnDisplay()
                || getTopDisplayFocusedStack() == targetStack)) {
            result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions); // 标注1️⃣
        }
        ...
            if (!resumedOnDisplay) {
                // In cases when there are no valid activities (e.g. device just booted or launcher
                // crashed) it's possible that nothing was resumed on a display. Requesting resume
                // of top activity in focused stack explicitly will make sure that at least home
                // activity is started and resumed, and no recursion occurs.
                final ActivityStack focusedStack = display.getFocusedStack();
                if (focusedStack != null) {
                    focusedStack.resumeTopActivityUncheckedLocked(target, targetOptions);  // 标注2️⃣
                }
            }
          ...

        return result;
    }
}

标注1️⃣和2️⃣的地方调用 ActivityStack.resumeTopActivityUncheckedLocked 方法:


class ActivityStack extends ConfigurationContainer {

    @GuardedBy("mService")
    boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
        ...
        result = resumeTopActivityInnerLocked(prev, options);
        ...
    }

    @GuardedBy("mService")
    private boolean resumeTopActivityInnerLocked(ActivityRecord prev, 
                                             ActivityOptions options) {
        ...
        if (anim) {
            next.applyOptionsLocked();
        } else {
            next.clearOptionsLocked();
        }
    
        mStackSupervisor.mNoAnimActivities.clear();
    
        if (next.attachedToProcess()) { // 待启动的进程是否创建完成,如果没有就会到 else 中
            ...
        }  else {
             // 标注1️⃣
             mStackSupervisor.startSpecificActivityLocked(next, true, true); 
        }
        ...
    }

}

标注1️⃣:调用 ActivityStackSupervisor.startSpecificActivityLocked:


public class ActivityStackSupervisor implements RecentTasks.Callbacks {
        void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
         ...
        try {
           ...
            // Post message to start process to avoid possible deadlock of calling into AMS with the
            // ATMS lock held.
            final Message msg = PooledLambda.obtainMessage(
                    // 标注1️⃣
                    ActivityManagerInternal::startProcess, mService.mAmInternal, r.processName,
                    r.info.applicationInfo, knownToBeDead, "activity", r.intent.getComponent());
            mService.mH.sendMessage(msg);
        } finally {
            Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
        }
    }
}

标注1️⃣:调用的其实是 ActivityManagerService内部类LocalService 的startProcess 方法,开始创建进程


public class ActivityManagerService extends IActivityManager.Stub
        implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
        @VisibleForTesting
    public final class LocalService extends ActivityManagerInternal {
        @Override
        public void startProcess(String processName, ApplicationInfo info,
                boolean knownToBeDead, String hostingType, ComponentName hostingName) {
            try {
                if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "startProcess:"
                            + processName);
                }
                synchronized (ActivityManagerService.this) {
                    // 标注1️⃣
                    startProcessLocked(processName, info, knownToBeDead, 0 /* intentFlags */,
                            new HostingRecord(hostingType, hostingName),
                            false /* allowWhileBooting */, false /* isolated */,
                            true /* keepIfLarge */);
                }
            } finally {
                Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
            }
        }
        
        // 标注1️⃣ 调用的方法
        @GuardedBy("this")
        final ProcessRecord startProcessLocked(String processName,
            ApplicationInfo info, boolean knownToBeDead, int intentFlags,
            HostingRecord hostingRecord, boolean allowWhileBooting,
            boolean isolated, boolean keepIfLarge) {
        // 标注2️⃣
        return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags,
                hostingRecord, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge,
                null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */,
                null /* crashHandler */);
    }
    }
}

标注1️⃣调用:LocalService.startProcessLocked 方法。
在 LocalService.startProcessLocked 方法中又把进程创建的工作委派给了 ProcessList。
标注2️⃣调用:ProcessList的startProcessLocked方法


public final class ProcessList {
    @GuardedBy("mService")
    final void startProcessLocked(ProcessRecord app, HostingRecord hostingRecord) {
        startProcessLocked(app, hostingRecord, null /* abiOverride */);
    }
    // 标注1️⃣ 调用的方法
    @GuardedBy("mService")
    final boolean startProcessLocked(ProcessRecord app, HostingRecord hostingRecord,
            String abiOverride) {
        // 标注2️⃣
        return startProcessLocked(app, hostingRecord,
                false /* disableHiddenApiChecks */, false /* mountExtStorageFull */, abiOverride);
    }
     @GuardedBy("mService")
    final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
            boolean knownToBeDead, int intentFlags, HostingRecord hostingRecord,
            boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge,
            String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {
        if (!isolated) {
            app = getProcessRecordLocked(processName, info.uid, keepIfLarge);
        }
        ...
         // 标注1️⃣ 
        final boolean success = startProcessLocked(app, hostingRecord, abiOverride);
        ...
        return success ? app : null;
    }

        /**
     * @return {@code true} if process start is successful, false otherwise.
     * @param app
     * @param hostingRecord
     * @param disableHiddenApiChecks
     * @param abiOverride
     */
    // 标注2️⃣ 调用的方法
    @GuardedBy("mService")
    boolean startProcessLocked(ProcessRecord app, HostingRecord hostingRecord,
            boolean disableHiddenApiChecks, boolean mountExtStorageFull,
            String abiOverride) {
      ...
           // 重点4️⃣:entryPoint 是新进程的入口。所以,Android 应用的程序入口是 ActivityThread。
            final String entryPoint = "android.app.ActivityThread";
            // 标注3️⃣
            return startProcessLocked(hostingRecord, entryPoint, app, uid, gids,
                    runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet, invokeWith,
                    startTime);
      ...
    }

    // 标注3️⃣ 调用的方法
        @GuardedBy("mService")
    boolean startProcessLocked(HostingRecord hostingRecord,
            String entryPoint,
            ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
            String seInfo, String requiredAbi, String instructionSet, String invokeWith,
            long startTime) {

          ...
          // 标注5️⃣
          final Process.ProcessStartResult startResult = startProcess(hostingRecord,
                        entryPoint, app,
                        uid, gids, runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet,
                        invokeWith, startTime);
                // 标注6️⃣
                handleProcessStartedLocked(app, startResult.pid, startResult.usingWrapper,
                        startSeq, false);
          ...
    }
       // 标注6️⃣ 调用的方法
        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) {
      ...
  // 标注7️⃣                    
  final AppZygote appZygote = createAppZygoteForProcessIfNeeded(app);
                // 标注8️⃣ 启动新的进程,入口是:ActivityThread.main()
                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,
                        /*useUsapPool=*/ false,
                        new String[] {PROC_START_SEQ_IDENT + app.startSeq});
      ...
    }
      // 标注7️⃣   调用的方法
        private AppZygote createAppZygoteForProcessIfNeeded(final ProcessRecord app) {
        synchronized (mService) {
            ...
            AppZygote appZygote = mAppZygotes.get(app.info.processName, uid);
            final ArrayList<ProcessRecord> zygoteProcessList;
            if (appZygote == null) {
                ...
               // 标注9️⃣  创建AppZygote
                appZygote = new AppZygote(appInfo, uid, firstUid, lastUid);
                mAppZygotes.put(app.info.processName, uid, appZygote);
                zygoteProcessList = new ArrayList<ProcessRecord>();
                mAppZygoteProcesses.put(appZygote, zygoteProcessList);
            } else {
               ...
                mService.mHandler.removeMessages(KILL_APP_ZYGOTE_MSG, appZygote);
                zygoteProcessList = mAppZygoteProcesses.get(appZygote);
            }
            ...
            zygoteProcessList.add(app);

            return appZygote;
        }
    }

}

标注9️⃣ : 创建AppZygote
标注8️⃣: 启动新的进程,入口是:ActivityThread.main(), 其中appZygote.getProcess()获取的是ChildZygoteProcess这个对象,ChildZygoteProcess又是ZygoteProcess的子类,也即是最终会调用ZygoteProcess.start方法


public class AppZygote {
        /**
     * Returns the zygote process associated with this app zygote.
     * Creates the process if it's not already running.
     */
    public ChildZygoteProcess getProcess() {
        synchronized (mLock) {
            if (mZygote != null) return mZygote;

            connectToZygoteIfNeededLocked();
            return mZygote;
        }
    }
}
// ChildZygoteProcess 的父类是 ZygoteProcess 
public class ChildZygoteProcess extends ZygoteProcess {
    /**
     * The PID of the child zygote process.
     */
    private final int mPid;

    ChildZygoteProcess(LocalSocketAddress socketAddress, int pid) {
        super(socketAddress, null);
        mPid = pid;
    }

    /**
     * Returns the PID of the child-zygote process.
     */
    public int getPid() {
        return mPid;
    }
}
public class ZygoteProcess {
  public final Process.ProcessStartResult start(@NonNull final String processClass,
                                                  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,
                                                  boolean useUsapPool,
                                                  @Nullable String[] zygoteArgs) {
        ...

        try {
            // 标注1️⃣
            return startViaZygote(processClass, niceName, uid, gid, gids,
                    runtimeFlags, mountExternal, targetSdkVersion, seInfo,
                    abi, instructionSet, appDataDir, invokeWith, /*startChildZygote=*/ false,
                    packageName, useUsapPool, zygoteArgs);
        } catch (ZygoteStartFailedEx ex) {
            Log.e(LOG_TAG,
                    "Starting VM process through Zygote failed");
            throw new RuntimeException(
                    "Starting VM process through Zygote failed", ex);
        }
    }
    // 标注1️⃣调用的方法
    private Process.ProcessStartResult startViaZygote(@NonNull final String processClass,
                                                      @Nullable final String niceName,
                                                      final int uid, final int gid,
                                                      @Nullable final int[] gids,
                                                      int runtimeFlags, int mountExternal,
                                                      int targetSdkVersion,
                                                      @Nullable String seInfo,
                                                      @NonNull String abi,
                                                      @Nullable String instructionSet,
                                                      @Nullable String appDataDir,
                                                      @Nullable String invokeWith,
                                                      boolean startChildZygote,
                                                      @Nullable String packageName,
                                                      boolean useUsapPool,
                                                      @Nullable String[] extraArgs)
                                                      throws ZygoteStartFailedEx {
            synchronized(mLock) {
            // The USAP pool can not be used if the application will not use the systems graphics
            // driver.  If that driver is requested use the Zygote application start path.
            // 标注3️⃣ 使用socket调用
            return 
zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi),
                                              useUsapPool,
                                              argsForZygote);
        }
    }
}

此时还处于 system_server进程,这个类的目的是创建本地的 Socket 连接对象,连接到 Zygote 进程的 Socket 方法,然后通过字符输入流,把创建进程所需要的参数发送过去。


三、Zygote 进程接收请求并创建 Launcher 进程

Zygote fork 出了 App进程,并把接下来的 Launcher 启动任务交给了 ActivityThread 来进行,接下来就从 ActivityThread.main 方法来分析 Launcher 的创建过程。

public final class ActivityThread extends ClientTransactionHandler {
    public static void main(String[] args) {
        Looper.prepareMainLooper();
         ...
        ActivityThread thread = new ActivityThread();
        thread.attach(false, startSeq);
        ...
        Looper.loop();
    }     

    @UnsupportedAppUsage
    private void attach(boolean system, long startSeq) {
      if (!system) {
            ...
            // 标注1️⃣ IActivityManager 是 AMS的代理类,最终会走到AMS的 attachApplication方法
            final IActivityManager mgr = ActivityManager.getService();
            try {
                mgr.attachApplication(mAppThread, startSeq);
            } catch (RemoteException ex) {
                throw ex.rethrowFromSystemServer();
            }
            ...
        }
    }

}
public class ActivityManagerService extends IActivityManager.Stub
        implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
    @VisibleForTesting
    public ActivityTaskManagerInternal mAtmInternal;
    public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
        // 调用已初始化过的内部类LocalService
        mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);
    }

   private void start() {
      ...
      // 初始化内部类的LocalService
       LocalServices.addService(ActivityManagerInternal.class, new LocalService());
      ...
    }
        @Override
    public final void attachApplication(IApplicationThread thread, long startSeq) {
        synchronized (this) {
            int callingPid = Binder.getCallingPid();
            final int callingUid = Binder.getCallingUid();
            final long origId = Binder.clearCallingIdentity();
            // 标注1️⃣
            attachApplicationLocked(thread, callingPid, callingUid, startSeq);
            Binder.restoreCallingIdentity(origId);
        }
    }

    public ActivityTaskManagerInternal mAtmInternal;
    @GuardedBy("this")
    private boolean attachApplicationLocked(@NonNull IApplicationThread thread,
                                        int pid, int callingUid, long startSeq) {
        ...
         // 标注2️⃣
        didSomething =   mAtmInternal.attachApplication(app.getWindowProcessController()); // 2
        ...
    }

       @VisibleForTesting
    public final class LocalService extends ActivityManagerInternal {
        @HotPath(caller = HotPath.PROCESS_CHANGE)
        @Override
        public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
            synchronized (mGlobalLockWithoutBoost) {
                // // 标注3️⃣
                return mRootActivityContainer.attachApplication(wpc);
            }
        }
    }
}

标注1️⃣:调用了 ActivityManagerService.attachApplicationLocked 方法
标注2️⃣ : mAtmInternal 是 ActivityTaskManagerInternal 类型的变量, ActivityTaskManagerService 中的内部类 LocalService 继承自 ActivityTaskManagerInternal,上述代码可以知道 mAtmInternal 实际上是LocalService 的对象
标注3️⃣ :调用RootActivityContainer的attachApplication()方法


    boolean attachApplication(WindowProcessController app) throws RemoteException {
        final String processName = app.mName;
        boolean didSomething = false;
        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
            final ActivityDisplay display = mActivityDisplays.get(displayNdx);
            final ActivityStack stack = display.getFocusedStack();
            if (stack != null) {
                stack.getAllRunningVisibleActivitiesLocked(mTmpActivityList);
                final ActivityRecord top = stack.topRunningActivityLocked();
                final int size = mTmpActivityList.size();
                for (int i = 0; i < size; i++) {
                    final ActivityRecord activity = mTmpActivityList.get(i);
                    if (activity.app == null && app.mUid == activity.info.applicationInfo.uid
                            && processName.equals(activity.processName)) {
                        try {
                          // 标注1️⃣
                            if (mStackSupervisor.realStartActivityLocked(activity, app,
                                    top == activity /* andResume */, true /* checkConfig */)) {
                                didSomething = true;
                            }
                        } catch (RemoteException e) {
                            Slog.w(TAG, "Exception in new application when starting activity "
                                    + top.intent.getComponent().flattenToShortString(), e);
                            throw e;
                        }
                    }
                }
            }
        }
        if (!didSomething) {
            ensureActivitiesVisible(null, 0, false /* preserve_windows */);
        }
        return didSomething;
    }

标注1️⃣:调用ActivityStackSupervisor的realStartActivityLocked()方法


public class ActivityStackSupervisor implements RecentTasks.Callbacks {
    boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
                                boolean andResume, boolean checkConfig) throws RemoteException {
        ...
        clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
                         System.identityHashCode(r), r.info,  
                         mergedConfiguration.getGlobalConfiguration(),
                         mergedConfiguration.getOverrideConfiguration(), r.compat,
                         r.launchedFromPackage, task.voiceInteractor,             
                         proc.getReportedProcState(), r.icicle, r.persistentState, results, 
                         newIntents, dc.isNextTransitionForward(),
                         proc.createProfilerInfoIfNeeded(), r.assistToken)); // 1

       // Set desired final state.
         final ActivityLifecycleItem lifecycleItem;
         if (andResume) {
              // 调用到Activity 的Resume方法
              lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
         } else {
              // 调用到Activity 的Pause方法
              lifecycleItem = PauseActivityItem.obtain();
         }
           clientTransaction.setLifecycleStateRequest(lifecycleItem);
        // Schedule transaction.
        //标注1️⃣
    mService.getLifecycleManager().scheduleTransaction(clientTransaction); 
        ...
    }
}

标注1️⃣: 调用ClientLifecycleManager的scheduleTransaction()方法


class ClientLifecycleManager {
     /**
     * Schedule a transaction, which may consist of multiple callbacks and a lifecycle request.
     * @param transaction A sequence of client transaction items.
     * @throws RemoteException
     *
     * @see ClientTransaction
     */
    void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
         // 标注1️⃣
        final IApplicationThread client = transaction.getClient();
        // 标注2️⃣
        transaction.schedule();
        if (!(client instanceof Binder)) {
            // If client is not an instance of Binder - it's a remote call and at this point it is
            // safe to recycle the object. All objects used for local calls will be recycled after
            // the transaction is executed on client in ActivityThread.
            transaction.recycle();
        }
    }
}

标注1️⃣: 调用ClientTransaction的getClient()方法
标注2️⃣: 调用ClientTransaction的schedule()方法


public class ClientTransaction implements Parcelable, ObjectPoolItem {
    /** Get the target client of the transaction. */
    public IApplicationThread getClient() {
        // 标注1️⃣
         return mClient;
    }

        /**
     * Schedule the transaction after it was initialized. It will be send to client and all its
     * individual parts will be applied in the following sequence:
     * 1. The client calls {@link #preExecute(ClientTransactionHandler)}, which triggers all work
     *    that needs to be done before actually scheduling the transaction for callbacks and
     *    lifecycle state request.
     * 2. The transaction message is scheduled.
     * 3. The client calls {@link TransactionExecutor#execute(ClientTransaction)}, which executes
     *    all callbacks and necessary lifecycle transitions.
     */
    public void schedule() throws RemoteException {
        // 标注2️⃣
        mClient.scheduleTransaction(this);
    }
}

标注1️⃣: mClient是 IApplicationThread 实例,IApplicationThread 是ApplicationThread 的代理类
标注2️⃣: 代表调用的是ApplicationThread 的scheduleTransaction()方法。注:ApplicationThread 是ActivityThread 的内部类。


public final class ActivityThread extends ClientTransactionHandler {
    private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);
    void sendMessage(int what, Object obj) {
        sendMessage(what, obj, 0, 0, false);
    }

    private void sendMessage(int what, Object obj, int arg1) {
        sendMessage(what, obj, arg1, 0, false);
    }

    private void sendMessage(int what, Object obj, int arg1, int arg2) {
        sendMessage(what, obj, arg1, arg2, false);
    }

    private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
        if (DEBUG_MESSAGES) {
            Slog.v(TAG,
                    "SCHEDULE " + what + " " + mH.codeToString(what) + ": " + arg1 + " / " + obj);
        }
        Message msg = Message.obtain();
        msg.what = what;
        msg.obj = obj;
        msg.arg1 = arg1;
        msg.arg2 = arg2;
        if (async) {
            msg.setAsynchronous(true);
        }
        // 标注3️⃣
        mH.sendMessage(msg);
    }
    
    //内部类
  class H extends Handler {
       public static final int EXECUTE_TRANSACTION = 159;
       public void handleMessage(Message msg) {
            if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
            switch (msg.what) {
              ...
                 case EXECUTE_TRANSACTION:
                    final ClientTransaction transaction = (ClientTransaction) msg.obj;
                    // 标注4️⃣
                    mTransactionExecutor.execute(transaction);
                    if (isSystem()) {
                        // Client transactions inside system process are recycled on the client side
                        // instead of ClientLifecycleManager to avoid being cleared before this
                        // message is handled.
                        transaction.recycle();
                    }
                    // TODO(lifecycler): Recycle locally scheduled transactions.
                    break;
              ...
            }
        }
    }

    // 内部类
    private class ApplicationThread extends IApplicationThread.Stub {
        @Override
        public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
           // 标注1️⃣
            ActivityThread.this.scheduleTransaction(transaction);
        }
    }
}

// ActivityThread 的父类ClientTransactionHandler 
public abstract class ClientTransactionHandler {
    void scheduleTransaction(ClientTransaction transaction) {
        transaction.preExecute(this);
        // 标注2️⃣
        sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
    }
    
    abstract void sendMessage(int what, Object obj);
}

标注1️⃣: 调用的是ActivityThread的scheduleTransaction方法,因为ActivityThread继承父类ClientTransactionHandler,scheduleTransaction()方法在ClientTransactionHandler类里面,所以调用的是ClientTransactionHandler的scheduleTransaction()方法
标注2️⃣: 调用 抽象方法sendMessage(),既是调用ActivityThread 的sendMessage()方法。这里的最终调用Hadler发送Message,其中msg.what则为:ActivityThread.H.EXECUTE_TRANSACTION
标注3️⃣:Handler 使用sendMessage发送Message 数据
标注4️⃣:调用TransactionExecutor发送execute


public class TransactionExecutor {
  private ClientTransactionHandler mTransactionHandler;
 
  public TransactionExecutor(ClientTransactionHandler clientTransactionHandler) {
         // 标注1️⃣
        mTransactionHandler = clientTransactionHandler;
  }
  public void execute(ClientTransaction transaction) {
      ...
      executeCallbacks(transaction); // 最终调用的是LaunchActivityItem的execute方法

      executeLifecycleState(transaction);// 最终调用的是ResumeActivityItem的execute方法
      mPendingActions.clear();
    }

    @VisibleForTesting
    public void executeCallbacks(ClientTransaction transaction) {
      ...
      // 标注2️⃣
      final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
      final int size = callbacks.size();
      for (int i = 0; i < size; ++i) {
          final ClientTransactionItem item = callbacks.get(i);
          ...
          // 标注3️⃣
          item.execute(mTransactionHandler, token, mPendingActions); // 2
          ..
      }

          /** Transition to the final state if requested by the transaction. */
    private void executeLifecycleState(ClientTransaction transaction) {
        // 标注4️⃣
        final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
        if (lifecycleItem == null) {
            // No lifecycle request, return early.
            return;
        }
        ...
        // Execute the final transition with proper parameters.
        // 标注5️⃣
        lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
         // 标注6️⃣
        lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
    }
}


-------------------------------------------------------------------------
public interface BaseClientRequest extends ObjectPoolItem {
    ...
    default void preExecute(ClientTransactionHandler client, IBinder token) {
    }
    void execute(ClientTransactionHandler client, IBinder token,
            PendingTransactionActions pendingActions);

    default void postExecute(ClientTransactionHandler client, IBinder token,
            PendingTransactionActions pendingActions) {
    }
    ...
}

public abstract class ClientTransactionItem implements BaseClientRequest, Parcelable {
    
}

public abstract class ActivityLifecycleItem extends ClientTransactionItem {
}

标注1️⃣: 追随上述代码查看可以知道mTransactionHandler实际是ActivityThread ,因为ActivityThread 继承ClientTransactionHandler 。
标注2️⃣: ClientTransaction 调用getCallbacks()方法获取到ClientTransactionItem列表信息,追随代码往上看,可以看到在ActivityStackSupervisor的realStartActivityLocked()方法中有调用到ClientTransaction 的addCallback方法,其中添加的是LaunchActivityItem这个类。查看源码可知道LaunchActivityItem 继承 ClientTransactionItem。
LaunchActivityItem launchActivityItem = LaunchActivityItem.obtain();
标注3️⃣: 调用ClientTransactionItem 的 execute()方法,
execute()方法是BaseClientRequest接口的,ClientTransactionItem 实现接口 BaseClientRequest。又因LaunchActivityItem 继承 ClientTransactionItem,所以最终调用的是LaunchActivityItem 的execute()方法,第一个参数mTransactionHandler传进去的是ActivityThread 。


标注4️⃣:ClientTransaction 调用getLifecycleStateRequest()方法获取到ActivityLifecycleItem ,追随代码往上看,可以看到在ActivityStackSupervisor的realStartActivityLocked()方法中有调用到ClientTransaction 的setLifecycleStateRequest方法,其中添加的是ResumeActivityItem或者PauseActivityItem其中的一个个类。查看源码可知道ResumeActivityItem与PauseActivityItem都继承ActivityLifecycleItem , ActivityLifecycleItem 继承ClientTransactionItem。
代码展现:
ActivityLifecycleItem activityLifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
ActivityLifecycleItem activityLifecycleItem = PauseActivityItem.obtain();
标注5️⃣: 调用ActivityLifecycleItem 的 execute()方法,
execute()方法是BaseClientRequest接口的,ClientTransactionItem 实现接口 BaseClientRequest。又因ActivityLifecycleItem 继承 ClientTransactionItem,所以最终调用的是LaunchActivityItem 的execute()方法,第一个参数mTransactionHandler传进去的是ActivityThread 。


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);
      // 标注1️⃣
        client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
        Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
    }
}

----------------------------------------------------------------------------

public class ResumeActivityItemextends ActivityLifecycleItem {
    @Override
    public void execute(ClientTransactionHandler client, IBinder token,
            PendingTransactionActions pendingActions) {
        Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityResume");
       // 标注2️⃣  
        client.handleResumeActivity(token, true /* finalStateRequest */, mIsForward,
                "RESUME_ACTIVITY");
        Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
    }
}

----------------------------------------------------------------------------

public class PauseActivityItem extends ActivityLifecycleItem {
    @Override
    public void execute(ClientTransactionHandler client, IBinder token,
            PendingTransactionActions pendingActions) {
        Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
         // 标注3️⃣
        client.handlePauseActivity(token, mFinished, mUserLeaving, mConfigChanges, pendingActions,
                "PAUSE_ACTIVITY_ITEM");
        Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
    }
}

上述代码可知,client 实际上是ActivityThread ,故此:
标注1️⃣:调用的是ActivityThread 的 handleLaunchActivity方法
标注2️⃣:调用的是ActivityThread 的 handleResumeActivity方法
标注3️⃣:调用的是ActivityThread 的 handlePauseActivity方法


public final class ActivityThread extends ClientTransactionHandler {
------------------------------调用Activity的onResume()----------------------------------------------
    @Override
    public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
            String reason) {
        ...
        // TODO Push resumeArgs into the activity for consideration
        final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
        ...
        final Activity a = r.activity;
        ...
        if (r.window == null && !a.mFinished && willBeVisible) {
            r.window = r.activity.getWindow();
            View decor = r.window.getDecorView();
            decor.setVisibility(View.INVISIBLE);
            ViewManager wm = a.getWindowManager();
            WindowManager.LayoutParams l = r.window.getAttributes();
            a.mDecor = decor;
            l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
            l.softInputMode |= forwardBit;
            if (r.mPreserveWindow) {
               ...
                ViewRootImpl impl = decor.getViewRootImpl();
                if (impl != null) {
                    impl.notifyChildRebuilt();
                }
            }
            if (a.mVisibleFromClient) {
                if (!a.mWindowAdded) {
                    a.mWindowAdded = true;
                    wm.addView(decor, l);
                } else {
                   ...
                    a.onWindowAttributesChanged(l);
                }
            }
            ...
        } else if (!willBeVisible) {
            ...
        }
         ...
            r.activity.mVisibleFromServer = true;
            mNumVisibleActivities++;
            if (r.activity.mVisibleFromClient) {
                // 调用Activity的makeVisible方法
                r.activity.makeVisible();
            }
          ...
    }

    public ActivityClientRecord performResumeActivity(IBinder token, boolean finalStateRequest,
            String reason) {
         ...
          // 调用Activity的performResume方法
            r.activity.performResume(r.startsNotResumed, reason);
         ...
    }
----------------------------------------------------------------------------

------------------------------调用Activity的onPause()----------------------------------------------
    @Override
    public void handlePauseActivity(IBinder token, boolean finished, boolean userLeaving,
            ...
           performPauseActivity(r, finished, reason, pendingActions);
            ...
    }

    private Bundle performPauseActivity(ActivityClientRecord r, boolean finished, String reason,
            PendingTransactionActions pendingActions) {
        ...
        performPauseActivityIfNeeded(r, reason);
        ...
    }

   private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) {
        ...
             // 调用Activity的callActivityOnPause方法
            Instrumentation.callActivityOnPause(r.activity);
        ...
    }
----------------------------------------------------------------------------

---------------------------Application与Activity生命周期调用-------------------------------------------------
  /**
     * Extended implementation of activity launch. Used when server requests a launch or relaunch.
     */
    @Override
    public Activity handleLaunchActivity(ActivityClientRecord r,
            PendingTransactionActions pendingActions, Intent customIntent) {
        ...
        // 标注1️⃣: 启动Activity
        final Activity a = performLaunchActivity(r, customIntent);
        ...
            // If there was an error, for any reason, tell the activity manager to stop us.
            try {
                // 标注2️⃣:停止 Activity 的启动
                ActivityTaskManager.getService()
                        .finishActivity(r.token, Activity.RESULT_CANCELED, null,
                                Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
            } catch (RemoteException ex) {
                throw ex.rethrowFromSystemServer();
            }
        ...
        return a;
    }


    /**  Core implementation of activity launch. */
    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
          // 标注3️⃣:获取 ActivityInfo 类
        ActivityInfo aInfo = r.activityInfo;
        if (r.packageInfo == null) {
            // 标注4️⃣:获取 APK 文件描述类 LoadApk
            r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
                    Context.CONTEXT_INCLUDE_CODE);
        }
        
        ComponentName component = r.intent.getComponent();
        ...
         // 标注5️⃣:创建要启动的 Activity 的上下文
        ContextImpl appContext = createBaseContextForActivity(r);
        Activity activity = null;
        try {
            java.lang.ClassLoader cl = appContext.getClassLoader();
            // 标注6️⃣ 用类加载器创建该 Activity 的实例
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
            StrictMode.incrementExpectedActivityCount(activity.getClass());
            ...
        } catch (Exception e) {
            ...
        }

        try {
            // 标注7️⃣  创建 Application,调用LoadedApk的makeApplication方法
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);
            ...
            if (activity != null) {
                ...
                // 标注8️⃣ 初始化 Activity,把上下文appContext绑定到activity
                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 (r.isPersistable()) {
                  // 标注9️⃣ 调用 Activity 的OnCreate方法
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                     // 标注9️⃣ 调用 Activity 的OnCreate方法
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
                ...
            }
            ...

        } catch (SuperNotCalledException e) {
            throw e;

        } catch (Exception e) {
            ...
        }

        return activity;
    }
}

四、Application与Activity初始化与生命周期的调用

1、调用LoadedApk的makeApplication方法初始化Application

往下看代码:

public final class LoadedApk {
      @UnsupportedAppUsage
    public Application makeApplication(boolean forceDefaultAppClass,
            Instrumentation instrumentation) {
        ...

        Application app = null;

        try {
           ...
            // 标注1️⃣ 创建上下文对象
            ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
            // 标注2️⃣ 创建Application,创建完之后调用attach()方法
            app = mActivityThread.mInstrumentation.newApplication(
                    cl, appClass, appContext);
            appContext.setOuterContext(app);
        } catch (Exception e) {
            ...
        }
      ...
        if (instrumentation != null) {
            try {
                // 标注3️⃣ 调用Application的onCreate()方法
                instrumentation.callApplicationOnCreate(app);
            } catch (Exception e) {
                ...
            }
        }
        ...
        return app;
    }
}

Instrumentation类的调用,用于调用各种生命周期方法

public class Instrumentation {
     public void callApplicationOnCreate(Application app) {
        // 标注1️⃣ 调用Application 的onCreate方法
        app.onCreate();
    }

   public void callActivityOnCreate(Activity activity, Bundle icicle) {
        prePerformCreate(activity);
        // 标注2️⃣ 调用Activity 的performCreate方法
        activity.performCreate(icicle);
        postPerformCreate(activity);
    }

    public void callActivityOnPause(Activity activity) {
       // 标注3️⃣ 调用Activity 的performPause方法
        activity.performPause();
    }
  
    public void callActivityOnResume(Activity activity) {
        // 标注3️⃣ 调用Activity 的onResume方法
        activity.onResume();
    }

    public void callActivityOnRestart(Activity activity) {
        // 标注4️⃣ 调用Activity 的onRestart方法
        activity.onRestart();
    }
}

Activity 类的调用各种生命周期方法

public class Activity extends ContextThemeWrapper
        implements LayoutInflater.Factory2,
        Window.Callback, KeyEvent.Callback,
        OnCreateContextMenuListener, ComponentCallbacks2,
        Window.OnWindowDismissedCallback, WindowControllerCallback,
        AutofillManager.AutofillClient, ContentCaptureManager.ContentCaptureClient {

   final void performCreate(Bundle icicle) {
        performCreate(icicle, null);
    }

    @UnsupportedAppUsage
    final void performCreate(Bundle icicle, PersistableBundle persistentState) {
        ...
        restoreHasCurrentPermissionRequest(icicle);
        if (persistentState != null) {
            onCreate(icicle, persistentState);
        } else {
            // 标注1️⃣ 调用onCreate
            onCreate(icicle);
        }
      ...
    }

 final void performResume(boolean followedByPause, String reason) {
     ...
     performRestart(true /* start */, reason);
     ...
      // 标注2️⃣ 调用Instrumentation的callActivityOnResume方法
     mInstrumentation.callActivityOnResume(this);
     ...
  }

  final void performRestart(boolean start, String reason) {
    // 标注3️⃣ 调用Instrumentation的callActivityOnRestart方法
    mInstrumentation.callActivityOnRestart(this);
  }

    // ActivityThread 的 handleResumeActivity()方法最后有调用到此方法
    void makeVisible() {
        if (!mWindowAdded) {
            ViewManager wm = getWindowManager();
            wm.addView(mDecor, getWindow().getAttributes());
            mWindowAdded = true;
        }
        mDecor.setVisibility(View.VISIBLE);
    }
}

总结:

一、整个流程涉及的主要角色有:

  1. Instrumentation: 监控应用与系统相关的交互行为。
  2. AMS:组件管理调度中心,什么都不干,但是什么都管。
  3. ActivityStarter:Activity 启动的控制器,处理 Intent 与 Flag 对Activity 启动的影响
    具体说来有:
    1️⃣ 寻找符合启动条件的 Activity,如果有多个,让用户选择;
    2️⃣ 校验启动参数的合法性;
    3️⃣ 返回 int 参数,代表 Activity是否启动成功。
  4. ActivityStackSupervisor:这个类的作用你从它的名字就可以看出来,它用来管理任务栈。
  5. ActivityStack:用来管理任务栈里的 Activity。
  6. ActivityThread:最终干活的人,Activity、Service、BroadcastReceiver 的启动、切换、调度等各种操作都在这个类里完成。

注:这里单独提一下 ActivityStackSupervisior,这是高版本才有的类,它用来管理多个 ActivityStack,早期的版本只有一个 ActivityStack 对应着手机屏幕,后来高版本支持多屏以后,就有了多个 ActivityStack,于是就引入了ActivityStackSupervisior 用来管理多个 ActivityStack。


二、整个流程主要涉及四个进程:

  1. 调用者进程,如果是在桌面启动应用就是 Launcher 应用进程。
  2. ActivityManagerService 等待所在的 System Server 进程,该进程主要运行着系统服务组件。
  3. Zygote 进程,该进程主要用来 fork 新进程。
  4. 新启动的应用进程,该进程就是用来承载应用运行的进程了,它也是应用的主线程(新创建的进程就是主线程),处理组件生命周期、界面绘制等相关事情。

三、Activity启动流程概括:

  1. 点击桌面App图标,Launcher进程采用Binder IPC向system_server(AMS)进程发起startActivity请求;
  2. system_server(AMS)进程接收到请求后,交付 ActivityStarter 处理 Intent 和 Flag 等信息,然后再交给 ActivityStackSupervisior/ActivityStack 处理 Activity 进栈相关流程。同时以 Socket 方式请求 Zygote 进程 fork 新进程。
  3. Zygote 接收到新进程创建请求后 fork 出新进程。
  4. App进程,通过Binder IPC向sytem_server(AMS)进程发起attachApplication请求;
  5. system_server(AMS)进程在收到请求后,进行一系列准备工作后,调用ActivityStackSupervisior的realStartActivityLocked,接着通过binder IPC向App进程调用ApplicationThread的scheduleTransaction方法;
  6. App进程的binder线程(ApplicationThread)在收到请求后,调用ActivityThread的scheduleTransaction()方法,接着通过handler向主线程发送ActivityThread.H.EXECUTE_TRANSACTION消息;
  7. 主线程在收到Message后,ActivityThread经过一些内部逻辑处理,最终调用handleLaunchActivity()、handleResumeActivity()方法,这俩方法又分别调用performLaunchActivity()、performResumeActivity()方法。

performLaunchActivity()方法里面逻辑顺序:

  • 创建ContextImpl 的实例appContext
  • 利用 ClassLoader 去加载 Activity并创建 Activity 实例。
  • 调用Activity 的attach方法,并把appContext 传进attach与Activity绑定,
    扩展:Activity 的attach方法里面会创建PhoneWindow实例,获取WindowManage实例,实际上是WindowManagerImpl(在SystemServiceRegistry里registerService中可以看到Context.WINDOW_SERVICE对应的是WindowManagerImpl)
  • 创建Application实例,并在LoadedApk类中调用Instrumentation 的callApplicationOnCreate去调用Application的onCreate()方法
  • 接着调用Instrumentation 的callActivityOnCreate()方法调用Activity的onCreate()方法

handleResumeActivity()方法里面逻辑顺序:

  • 首先会执行performResumeActivity去调用Activity的onStart()、onResume(),返回ActivityClientRecord实例,通过此实例获取Activity
  • 从Activity中获取PhoneWindow,
  • 然后从PhoneWindow中获取到DecorView
  • 接着从Activity中获取WindowManager(实际上是WindowManagerImpl)
  • 再继续WindowManagerImpl调用addView()方法把DecorView添加进去
  • WindowManagerImpld的addView()方法会调用到WindowManagerGlobal的addView()方法,在此方法中会创建ViewRootImpl的实例。
  • 最终会调用ViewRootImpl的setView()方法加载DecorView,执行绘制流程。
  1. 到此,App便正式启动,UI渲染结束后便可以看到App的主界面。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,634评论 6 497
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,951评论 3 391
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 161,427评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,770评论 1 290
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,835评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,799评论 1 294
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,768评论 3 416
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,544评论 0 271
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,979评论 1 308
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,271评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,427评论 1 345
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,121评论 5 340
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,756评论 3 324
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,375评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,579评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,410评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,315评论 2 352

推荐阅读更多精彩内容