Android 开发中心总是绕不过那几个模块,与 Android 的相关面试就离不开这个话题,什么,你又要开端讲述 Binder 的界说跟根底了?不不不,今天咱们从 Activity 的发动来剖析一波其间的代码原理和 ActivityTaskManagerService 进程间的通讯进程。

本章所有源码版别依据 android-30

在 Android 10.0 Q(api-29)之前,都是由 ActivityManagerService 这个服务来掌管 Activity 的中心工作,但是在 api-29 之后,便是由 ActivityTaskManagerService 接替 ActivityManagerService 来独自担任管理 activities 和 activity 相关容器(task,stacks,display)

在 app 运转进程中,不管是 Activity 之前的跳转,还是在手机桌面使用中点击一个 icon 发动这个app,终究都是去经过 startActivity 去翻开某一个 Activity 页面。咱们知道 Android 中的一个 App 就相当于一个进程,所以 startActivity 操作中还需求判别,方针 Activity 的进程是否现已创立,假如没有,则在显现 Activity 之前还需求将进程 Process 提早创立出来。

一文把握 Activity 的发动原理,依据android-30的源码剖析

所以整个 startActivity 的流程分为 4 大部分,也触及 4 个进程之间的交互:

  1. 使用进程(Launcher)调用 ActivityTaskManagerService 来创立 Activity
  2. ActivityTaskManagerService 到 ApplicationThread 的调用进程
  3. ActivityTaskManagerService 向 Zygote 发送启用使用进程
  4. ActivityThread 发动 Activity 的进程

1. 使用进程(Launcher)调用 ActivityTaskManagerService 阶段

这一进程并不复杂,看下源码中做了哪些操作。

Activity 的 startActivity

终究调用了 startActivityForResult 办法,传入的 -1 表示不需求获取 startActivity 的成果。

    @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);
        }
    }

Activity 的 startActivityForResult

详细代码如下所示:

    public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
            @Nullable Bundle options) {
        if (mParent == null) {
            options = transferSpringboardActivityOptions(options);
            // mMainThread.getApplicationThread()获取当时Activity的进程。
            Instrumentation.ActivityResult ar =
                mInstrumentation.execStartActivity(
                    this, mMainThread.getApplicationThread(), mToken, this,
                    intent, requestCode, options);
            if (ar != null) {
                mMainThread.sendActivityResult(
                    mToken, mEmbeddedID, requestCode, ar.getResultCode(),
                    ar.getResultData());
            }
            if (requestCode >= 0) {
                mStartedActivity = true;
            }
            cancelInputsAndStartExitTransition(options);
        } else {
            ...
        }
    }

startActivityForResult 也很简单,调用 Instrumentation.execStartActivity 办法。剩余的交给 Instrumentation 类去处理。

解释说明:

  • Instrumentation 类首要用来监控使用程序与体系交互。
  • mMainThread.getApplicationThread(),这个便是用来完结进程间通讯的,详细来说便是 AMS 所在体系进程告诉使用程序进程进行的一系列操作。

Instrumentation 的 execStartActivity

办法如下:

    @UnsupportedAppUsage
    public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {
        // 前置处理
        try {
            intent.migrateExtraStreamToClipData(who);
            intent.prepareToLeaveProcess(who);
            // ActivityTaskManager.getService() 获取 ActivityTaskManagerService 的实例
            int result = ActivityTaskManager.getService().startActivity(whoThread,
                    who.getBasePackageName(), who.getAttributionTag(), intent,
                    intent.resolveTypeIfNeeded(who.getContentResolver()), token,
                    target != null ? target.mEmbeddedID : null, requestCode, 0, null, options);
            checkStartActivityResult(result, intent);
        } catch (RemoteException e) {
            throw new RuntimeException("Failure from system", e);
        }
        return null;
    }

ActivityTaskManager.getService() 获取 ActivityTaskManagerService 的实例,是使用 ActivityTaskManagerService 来调用其 startActivity 办法。

    public static IActivityTaskManager getService() {
        return IActivityTaskManagerSingleton.get();
    }
    @UnsupportedAppUsage(trackingBug = 129726065)
    private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton =
            new Singleton<IActivityTaskManager>() {
                @Override
                protected IActivityTaskManager create() {
                    // "activity_task"
                    final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);
                    return IActivityTaskManager.Stub.asInterface(b);
                }
            };

咱们来看 getService 办法调用了 IActivityTaskManagerSingleton 的 get 办法,而它是一个 Singleton 类,在重写的 create 办法中获取 Context.ACTIVITY_TASK_SERVICE 的 IBinder 引用,然后转换成 IActivityTaskManager 类型的方针。典型的AIDL的写法,IActivityTaskManager 类是 AIDL 工具在编译时主动生成,要完结进程间通讯,服务端也便是 ActivityTaskManagerService 只需求承继 IActivityTaskManager.Stub 类并完结相应的办法就能够了。

经过 AIDL 来调用 ActivityTaskManagerService 的 startActivity 办法,至此,startActivity 的工作重心成功地从进程 Activity 搬运到了体系进程 ActivityTaskManagerService 中。

2. ActivityTaskManagerService 到 ApplicationThread 的调用进程

接下来就看下在 ActivityTaskManagerService 中是怎么一步一步履行到方针 Activity 进程的。

  1. 综合处理 launchMode 和 Intent 中的 Flag 标志位,并依据处理成果生成一个方针 Activity 的方针(ActivityRecord)。
  2. 判别是否需求为方针 Activity 创立一个新的进程(ProcessRecord)、新的使命栈(TaskRecord)。

接下来就从 ActivityTaskManagerService 的 startActivity 办法开端看起:

ActivityTaskManagerService 的 startActivity

    @Override
    public final int startActivity(IApplicationThread caller, String callingPackage,
            String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
            String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
            Bundle bOptions) {
        return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
                resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions,
                UserHandle.getCallingUserId());
    }
    private int startActivityAsUser(IApplicationThread caller, String callingPackage,
            @Nullable String callingFeatureId, Intent intent, String resolvedType,
            IBinder resultTo, String resultWho, int requestCode, int startFlags,
            ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {
        assertPackageMatchesCallingUid(callingPackage);
        // 判别调用者进程是否被阻隔,假如 isIsolated 则抛出 SecurityException 异常
        enforceNotIsolatedCaller("startActivityAsUser");
        // 查看调用者权限
        userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
                Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
        // TODO: Switch to user app stacks here.
        return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
                .setCaller(caller)
                .setCallingPackage(callingPackage)
                .setCallingFeatureId(callingFeatureId)
                .setResolvedType(resolvedType)
                .setResultTo(resultTo)
                .setResultWho(resultWho)
                .setRequestCode(requestCode)
                .setStartFlags(startFlags)
                .setProfilerInfo(profilerInfo)
                .setActivityOptions(bOptions)
                .setUserId(userId)
                .execute();
    }

startActivity 和 startActivityAsUser 的首要区别仅在于办法多了一个参数 UserHandle.getCallingUserId(),该办法会获取调用者的 UserId, ActivityTaskManagerService 能够依据这个 UserId 来确定调用者的权限。

终究经过 getActivityStartController().obtainStarter(intent, “startActivityAsUser”) 来获取 ActivityStarter 方针,调用 ActivityStarter 的 execute() 办法继续履行发动流程。

    int execute() {
        try {
            ...
            int res;
            synchronized (mService.mGlobalLock) {
                ...
                res = executeRequest(mRequest);
                Binder.restoreCallingIdentity(origId);
                ...
            }
        } finally {
            onExecutionComplete();
        }
    }

在 execute() 中,会再次调用其内部的 executeRequest 办法。

ActivityStarter 的 executeRequest

ActivityStarter 是 Android7.0 中新增的类, 它是用来加载Activity的控制类,看名字也想得到它是专门担任一个 Activity 的发动操作。它的首要作用包括解析 Intent、创立 ActivityRecord、假如有或许还要创立 TaskRecord。

executeRequest 是 ActivityStarter 的中心办法,部分完结如下:

    private int executeRequest(Request request) {
        ... 
        WindowProcessController callerApp = null;
        if (caller != null) {
            // 得到调用进程的信息
            callerApp = mService.getProcessController(caller);
            if (callerApp != null) {
                callingPid = callerApp.getPid();
                callingUid = callerApp.mInfo.uid;
            } else {
                Slog.w(TAG, "Unable to find app for caller " + caller + " (pid=" + callingPid
                        + ") when starting: " + intent.toString());
                err = ActivityManager.START_PERMISSION_DENIED;
            }
        }
        ...    
        //各种过错查看
        ...
        // 查看 intent 防火墙是否屏蔽了该 intent
        boolean abort = !mSupervisor.checkStartAnyActivityPermission(intent, aInfo, resultWho,
                requestCode, callingPid, callingUid, callingPackage, callingFeatureId,
                request.ignoreTargetSecurity, inTask != null, callerApp, resultRecord, resultStack);
        abort |= !mService.mIntentFirewall.checkStartActivity(intent, callingUid,
                callingPid, resolvedType, aInfo.applicationInfo);
        abort |= !mService.getPermissionPolicyInternal().checkStartActivity(intent, callingUid,
                callingPackage);
        ... ... 
        // If permissions need a review before any of the app components can run, we
        // launch the review activity and pass a pending intent to start the activity
        // we are to launching now after the review is completed.
        if (aInfo != null) {
            if (mService.getPackageManagerInternalLocked().isPermissionsReviewRequired(
                    aInfo.packageName, userId)) {
                ...
                // 经过 ActivityStackSupervisor 获取 ResolveInfo 信息
                rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId, 0,
                        computeResolveFilterUid(
                                callingUid, realCallingUid, request.filterCallingUid));
                // 经过 ActivityStackSupervisor 获取方针 Activity 信息 
                aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags,
                        null /*profilerInfo*/);
                ...
            }
        }
        if (rInfo != null && rInfo.auxiliaryInfo != null) {
            ...
            // 经过 ActivityStackSupervisor 获取方针 Activity 信息 
            aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, null /*profilerInfo*/);
        }
        // 创立 ActivityRecord 方针
        final ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,
                callingPackage, callingFeatureId, intent, resolvedType, aInfo,
                mService.getGlobalConfiguration(), resultRecord, resultWho, requestCode,
                request.componentSpecified, voiceSession != null, mSupervisor, checkedOptions,
                sourceRecord);
        mLastStartActivityRecord = r;
        ...
        mLastStartActivityResult = startActivityUnchecked(r, sourceRecord, voiceSession,
                request.voiceInteractor, startFlags, true /* doResume */, checkedOptions, inTask,
                restrictedBgActivity, intentGrants);
        return mLastStartActivityResult;
    }

能够看出获取方针 Activity 信息的操作由 ActivityStackSupervisor 来完结,首要是担任 Activity 所在栈的管理类。

ActivityStackSupervisor 中的 resolveIntent 中实际上是调用体系 PackageManagerService 来获取最佳 Activity。有时候咱们经过隐式 Intent 发动 Activity 时,体系中或许存在多个 Activity 能够处理 Intent,此刻会弹出一个挑选框让用户挑选详细需求翻开哪一个 Activity 界面,便是此处的逻辑处理成果。

在 executeRequest 办法的终究会调用 startActivityUnchecked 办法来获取发动 Activity 的成果。startActivityUnchecked 办法中采用 startActivityInner 来处理方针 Activity 的信息。

ActivityStarter 的 startActivityInner

@VisibleForTesting
    int startActivityInner(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, Task inTask,
            boolean restrictedBgActivity, NeededUriGrants intentGrants) {
        setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession,
                voiceInteractor, restrictedBgActivity);
        // 1. 核算发动 Activity 的 Flag 值
        computeLaunchingTaskFlags();
        ... ...
        // 2. 处理 Task 和 Activity 的进栈操作
        mTargetStack.startActivityLocked(mStartActivity, topStack.getTopNonFinishingActivity(),
                newTask, mKeepCurTransition, mOptions);
        // 3. 发动栈中顶部的 Activity
        if (mDoResume) {
            final ActivityRecord topTaskActivity =
                    mStartActivity.getTask().topRunningActivityLocked();
            if (!mTargetStack.isTopActivityFocusable()
                    || (topTaskActivity != null && topTaskActivity.isTaskOverlay()
                    && mStartActivity != topTaskActivity)) {
                ...
                mTargetStack.ensureActivitiesVisible(null /* starting */,
                        0 /* configChanges */, !PRESERVE_WINDOWS);
                mTargetStack.getDisplay().mDisplayContent.executeAppTransition();
            } else {
                ...
                mRootWindowContainer.resumeFocusedStacksTopActivities(
                        mTargetStack, mStartActivity, mOptions);
            }
        }
        mRootWindowContainer.updateUserStack(mStartActivity.mUserId, mTargetStack);
        return START_SUCCESS;
    }

当时办法首要处理了发动 Activity 的 Flag 值、Task 和 Activity 的进栈操作以及发动栈中顶部的 Activity的相应操作,咱们详细一步一步剖析。

computeLaunchingTaskFlags 办法详细如下:

    private void computeLaunchingTaskFlags() {
        ... 前置处理 Task 和 Intent 的信息
        if (mInTask == null) {
            if (mSourceRecord == null) {
                // 使用 Context 或许 Application 发动 Activity 时,mSourceRecord 为空
                if ((mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) == 0 && mInTask == null) {
                    Slog.w(TAG, "startActivity called from non-Activity context; forcing " +
                            "Intent.FLAG_ACTIVITY_NEW_TASK for: " + mIntent);
                    mLaunchFlags |= FLAG_ACTIVITY_NEW_TASK;
                }
            } else if (mSourceRecord.launchMode == LAUNCH_SINGLE_INSTANCE) {
                // 初始 Activity 假如是在 SingleInstance 栈中的 Activity,这种需求添加 NEW_TASK 的标识。
                // 由于 SingleInstance 栈只能允许保存一个 Activity。
                mLaunchFlags |= FLAG_ACTIVITY_NEW_TASK;
            } else if (isLaunchModeOneOf(LAUNCH_SINGLE_INSTANCE, LAUNCH_SINGLE_TASK)) {
                // 假如 Launch Mode 设置了 singleTask 或 singleInstance,则也要创立一个新栈。
                mLaunchFlags |= FLAG_ACTIVITY_NEW_TASK;
            }
        }
    }

这个办法的前置部分处理完 Task 和 Intent 的信息,依据 Task 和 ActivityRecord 的类型来判别怎么给方针 Activity 增加相应的发动 Flag。不同的 Flag 决定了发动 Activity 终究会被放置到哪一个 Task 调集中。

ActivityStackSupervisor 的 startActivityLocked

void startActivityLocked(ActivityRecord r, ActivityRecord focusedTopActivity,
            boolean newTask, boolean keepCurTransition, ActivityOptions options) {
        Task rTask = r.getTask();
        final boolean allowMoveToFront = options == null || !options.getAvoidMoveToFront();
        final boolean isOrhasTask = rTask == this || hasChild(rTask);
        // mLaunchTaskBehind tasks get placed at the back of the task stack.
        if (!r.mLaunchTaskBehind && allowMoveToFront && (!isOrhasTask || newTask)) {
            // Last activity in task had been removed or ActivityManagerService is reusing task.
            // Insert or replace.
            // Might not even be in.
            positionChildAtTop(rTask);
        }
        ...
    }

办法中会调用 positionChildAtTop 办法测验将 Task 和 Activity 入栈。假如 Activity 是以 newTask 的模式发动或许 TASK 堆栈中不存在该 Task id,则 Task 会重新入栈,而且放在栈的顶部。需求注意的是:Task 先入栈,之后才是 Activity 入栈,它们是包括关系。

RootWindowContainer 的 resumeFocusedStacksTopActivities 和 updateUserStack

在 RootWindowContainer 的 resumeTopActivityUncheckedLocked 办法中经过一系列调用,期间经过ActivityStack 处理、终究代码到了 ActivityStackSupervisor 中的 startSpecificActivity 办法。

ActivityStackSupervisor 的 startSpecificActivity

    void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) {
        // 依据进程名称和 Application 的 uid 来判别方针进程是否现已创立,假如没有则代表进程未创立。
        final WindowProcessController wpc =
                mService.getProcessController(r.processName, r.info.applicationInfo.uid);
        boolean knownToBeDead = false;
        if (wpc != null && wpc.hasThread()) {
            try {
                // 履行发动 Activity 的操作
                realStartActivityLocked(r, wpc, andResume, checkConfig);
                return;
            } catch (RemoteException e) {
                Slog.w(TAG, "Exception when starting activity "
                        + r.intent.getComponent().flattenToShortString(), e);
            }
            // If a dead object exception was thrown -- fall through to
            // restart the application.
            knownToBeDead = true;
        }
        r.notifyUnknownVisibilityLaunchedForKeyguardTransition();
        final boolean isTop = andResume && r.isTopRunningActivity();
        // 调用 ActivityTaskManagerService 创立 Activity 所在进程。
        mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity");
    }

依据源码咱们发现不管是方针进程是否为新建,终究都会调用 realStartActivityLocked 办法来履行发动 Activity 的操作。

ActivityStackSupervisor 的 realStartActivityLocked

boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
            boolean andResume, boolean checkConfig) throws RemoteException {
        ...
        try {
            ...
            try {
                ...
                // Activity 的发动交给了业务(Transaction)来完结
                // Create activity launch transaction.
                final ClientTransaction clientTransaction = ClientTransaction.obtain(
                        proc.getThread(), r.appToken);
                final DisplayContent dc = r.getDisplay().mDisplayContent;
                clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
                        System.identityHashCode(r), r.info,
                        // TODO: Have this take the merged configuration instead of separate global
                        // and override configs.
                        mergedConfiguration.getGlobalConfiguration(),
                        mergedConfiguration.getOverrideConfiguration(), r.compat,
                        r.launchedFromPackage, task.voiceInteractor, proc.getReportedProcState(),
                        r.getSavedState(), r.getPersistentSavedState(), results, newIntents,
                        dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(),
                        r.assistToken, r.createFixedRotationAdjustmentsIfNeeded()));
                // Set desired final state.
                final ActivityLifecycleItem lifecycleItem;
                if (andResume) {
                    lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
                } else {
                    lifecycleItem = PauseActivityItem.obtain();
                }
                clientTransaction.setLifecycleStateRequest(lifecycleItem);
                // Schedule transaction.
                mService.getLifecycleManager().scheduleTransaction(clientTransaction);
                ...
            } catch (RemoteException e) {
                throw e;
            }
        } finally {
            endDeferResume();
        }
        ...
        return true;
    }

能够看到 Activity 的发动交给了业务(ClientTransaction)来完结。由 ClientTransaction 来创立 Activity 发动业务,并传入 app.thread 参数,并在之后调用 scheduleTransaction 办法来履行 Activity 发动业务。

Activity 发动业务的履行是由 ClientLifecycleManager 来完结的,详细代码如下:

    void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
        final IApplicationThread client = transaction.getClient();
        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();
        }
    }

能够看出实际上是调用了发动业务 ClientTransaction 的 schedule 办法,而这个 transaction 实际上是在创立 ClientTransaction 时传入的 app.thread 方针,也便是 ApplicationThread。如下所示:

    /** Obtain an instance initialized with provided params. */
    public static ClientTransaction obtain(IApplicationThread client, IBinder activityToken) {
        ClientTransaction instance = ObjectPool.obtain(ClientTransaction.class);
        if (instance == null) {
            instance = new ClientTransaction();
        }
        instance.mClient = client;
        instance.mActivityToken = activityToken;
        return instance;
    }

传入的 app.thread 会赋值给 ClientTransaction 的成员变量 mClient,所以 mClient 变量便是 IApplicationThread 方针即 ActivityThread 的内部类 ApplicationThread,其间 ApplicationThread 承继了 IApplicationThread.Stub。 所以业务终究是调用 app.thread 的 scheduleTransaction 履行。这儿经过 IApplicationThread 来与使用进程进行 Binder 通讯。所以代码回到了 ApplicationThread.ActivityThread 上。

到这为止 startActivity 操作就成功地从 ActivityTaskManagerService 搬运到了方针 Activity 中的 ApplicationThread 中,剩余的便是 ActivityTaskManagerService 经过进程间通讯机制告诉 ApplicationThread 履行 Activity 的生命周期办法。

3. ActivityTaskManagerService 向 Zygote 发送启用使用进程

在之前 ActivityStackSupervisor 的 startSpecificActivity 办法中,咱们看到由 ActivityTaskManagerService 的 startProcessAsync 办法来恳求发动新的使用进程。细心查看其间首要是调用了 ActivityManagerService 的 startProcess 办法

ActivityManagerService 的 startProcess

// ActivityManagerInternal 类
/** Starts a given process. */
public abstract void startProcess(String processName, ApplicationInfo info,
        boolean knownToBeDead, boolean isTop, String hostingType, ComponentName hostingName);
// ActivityManagerService 类
@Override
public void startProcess(String processName, ApplicationInfo info, boolean knownToBeDead,
        boolean isTop, 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) {
            // If the process is known as top app, set a hint so when the process is
            // started, the top priority can be applied immediately to avoid cpu being
            // preempted by other processes before attaching the process of top app.
            startProcessLocked(processName, info, knownToBeDead, 0 /* intentFlags */,
                    new HostingRecord(hostingType, hostingName, isTop),
                    ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE, false /* allowWhileBooting */,
                    false /* isolated */);
        }
    } finally {
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
    }
}

里边首要是 startProcessLocked 办法

    @GuardedBy("this")
    final ProcessRecord startProcessLocked(String processName,
            ApplicationInfo info, boolean knownToBeDead, int intentFlags,
            HostingRecord hostingRecord, int zygotePolicyFlags, boolean allowWhileBooting,
            boolean isolated, boolean keepIfLarge) {
        return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags,
                hostingRecord, zygotePolicyFlags, allowWhileBooting, isolated, 0 /* isolatedUid */,
                keepIfLarge, null /* ABI override */, null /* entryPoint */,
                null /* entryPointArgs */, null /* crashHandler */);
    }

依据一系列的调用,终究能够看到是由 ProcessList 中的 startProcess 办法处理,中心是进行到 Process 的 start 办法。

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,
                                           int zygotePolicyFlags,
                                           boolean isTopApp,
                                           @Nullable long[] disabledCompatChanges,
                                           @Nullable Map<String, Pair<String, Long>>
                                                   pkgDataInfoMap,
                                           @Nullable Map<String, Pair<String, Long>>
                                                   whitelistedDataInfoMap,
                                           boolean bindMountAppsData,
                                           boolean bindMountAppStorageDirs,
                                           @Nullable String[] zygoteArgs) {
        return ZYGOTE_PROCESS.start(processClass, niceName, uid, gid, gids,
                    runtimeFlags, mountExternal, targetSdkVersion, seInfo,
                    abi, instructionSet, appDataDir, invokeWith, packageName,
                    zygotePolicyFlags, isTopApp, disabledCompatChanges,
                    pkgDataInfoMap, whitelistedDataInfoMap, bindMountAppsData,
                    bindMountAppStorageDirs, zygoteArgs);
    }

不难发现 Process 的 start 办法只调用了 ZYGOTE_PROCESS 的 start 办法,ZYGOTE_PROCESS 类是用于坚持与 Zygote 进程的通讯状况。

ZygoteProcess 中的 start 办法中心是调用了 startViaZygote 办法,在这个办法终究咱们发现

        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.
            return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi),
                                              zygotePolicyFlags,
                                              argsForZygote);
        }

这儿面的第一个参数调用了openZygoteSocketIfNeeded办法,这儿会调用 ZygoteState 的 connect 办法与 Zygote 树立连接。

而 ZygoteProcess 的 zygoteSendArgsAndGetResult 办法首要是将传入的使用进程的发动参数 argsForZygote 写入到 ZygoteState 中。

到此就完结了 ActivityTaskManagerService 向 Zygote 发送启用使用进程。

4. ActivityThread 发动 Activity 的进程

在第三个章节咱们剖析了 ActivityTaskManagerService 将发动 Activity 的使命作为一个业务 ClientTransaction 去完结,在 ClientLifecycleManager 中会调用 ClientTransaction的schedule() 办法,而 mClient 是一个 IApplicationThread 接口类型,详细完结是 ActivityThread 的内部类 ApplicationThread。因而后续履行 Activity 生命周期的进程都是由 ApplicationThread 指导完结的,而调用 ActivityThread 的 scheduleTransaction 办法,而 ActivityThread 是承继自抽象类 ClientTransactionHandler,ActivityThread 没有重写该办法,所以这儿就会调用到 ClientTransactionHandler 的 scheduleTransaction 办法。详细如下:

public abstract class ClientTransactionHandler {
    // Schedule phase related logic and handlers.
    /** Prepare and schedule transaction for execution. */
    void scheduleTransaction(ClientTransaction transaction) {
        transaction.preExecute(this);
        sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
    }
}

调用 sendMessage 办法,向 Handler 中发送了一个 EXECUTE_TRANSACTION 的音讯,而且 Message 中的 obj 便是发动 Activity 的业务方针。而这个 Handler 的详细完结是 ActivityThread 中的 mH 方针。源码如下:

public final class ActivityThread extends ClientTransactionHandler
        implements ActivityThreadInternal {
    @UnsupportedAppUsage
    final H mH = new H();
    final Executor mExecutor = new HandlerExecutor(mH);
    class H extends Handler {
         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;
                    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;
            }
         }
    }
}

能够看到这个音讯被 TransactionExecutor 处理了,履行了其间的 execute 办法

    public void execute(ClientTransaction transaction) {
        ...
        executeCallbacks(transaction);
        executeLifecycleState(transaction);
        mPendingActions.clear();
        if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "End resolving transaction");
    }

内部是由 executeCallback 办法处理的

TransactionExecutor 的 executeCallback

    @VisibleForTesting
    public void executeCallbacks(ClientTransaction transaction) {
        final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
        ...
        final int size = callbacks.size();
        for (int i = 0; i < size; ++i) {
            final ClientTransactionItem item = callbacks.get(i);
            if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "Resolving callback: " + item);
            final int postExecutionState = item.getPostExecutionState();
            final int closestPreExecutionState = mHelper.getClosestPreExecutionState(r,
                    item.getPostExecutionState());
            if (closestPreExecutionState != UNDEFINED) {
                cycleToPath(r, closestPreExecutionState, transaction);
            }
            item.execute(mTransactionHandler, token, mPendingActions);
            item.postExecute(mTransactionHandler, token, mPendingActions);
            if (r == null) {
                // Launch activity request will create an activity record.
                r = mTransactionHandler.getActivityClient(token);
            }
            if (postExecutionState != UNDEFINED && r != null) {
                // Skip the very last transition and perform it by explicit state request instead.
                final boolean shouldExcludeLastTransition =
                        i == lastCallbackRequestingState && finalState == postExecutionState;
                cycleToPath(r, postExecutionState, shouldExcludeLastTransition, transaction);
            }
        }
    }

这儿 callbacks 列表中寄存的是第二阶段中 ActivityStackSupervisor 的 realStartActivityLocked 办法

中创立业务时设置进去的。即 LaunchActivityItem 所以这儿是履行 LaunchActivityItem 方针的 execute 办法。

LaunchActivityItem 的 execute()

    @Override
    public void execute(ClientTransactionHandler client, IBinder token,
            PendingTransactionActions pendingActions) {
        Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
        ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
                mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
                mPendingResults, mPendingNewIntents, mIsForward,
                mProfilerInfo, client, mAssistToken, mFixedRotationAdjustments);
        client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
        Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
    }

其间的 handleLaunchActivity 是不是以及非常熟悉了,终于到了跟 Activity 生命周期相关的办法了,源码中 client 是 ClientTransationHandler 类型,实际完结类便是 ActivityThread。所以咱们能够看一下 ActivityThread 中的 handleLaunchActivity 办法了。

ActivityThread 的 handleLaunchActivity

这是一个比较重要的办法,Activity 的生命周期办法便是在这个办法中有序履行,详细如下:

    @Override
    public Activity handleLaunchActivity(ActivityClientRecord r,
            PendingTransactionActions pendingActions, Intent customIntent) {
        ...
        // 初始化 Activity 的 WindowManager
        if (ThreadedRenderer.sRendererEnabled
                && (r.activityInfo.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0) {
            HardwareRenderer.preload();
        }
        WindowManagerGlobal.initialize();
        // Hint the GraphicsEnvironment that an activity is launching on the process.
        GraphicsEnvironment.hintActivityLaunch();
        // 调用 performLaunchActivity 创立并显现 Activity
        final Activity a = performLaunchActivity(r, customIntent);
        ...
        return a;
    }

能够看到里边最中心的两个办法便是初始化 Activity 的 WindowManager,以及调用 performLaunchActivity 创立并显现 Activity。

ActivityThread 的 performLaunchActivity

    /**  Core implementation of activity launch. */
    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        ...
        Activity activity = null;
        try {
            // 经过反射创立方针 Activity 方针
            java.lang.ClassLoader cl = appContext.getClassLoader();
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
            StrictMode.incrementExpectedActivityCount(activity.getClass());
            ...
        } catch (Exception e) {
            ...
        }
        try {
            if (activity != null) {
                ...
                // 调用 attach 办法树立 Activity 与 Context 之间的联络,创立 PhoneWindow 方针,并与 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.activityConfigCallback,
                        r.assistToken, r.shareableActivityToken);
                ...
                // 经过 Instrumentation 终究调用 Activity 的 onCreate 办法
                if (r.isPersistable()) {
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
            }
        } catch (Exception e) {
            ...
        }
        return activity;
    }

能够看到在 performLaunchActivity 办法中首要完结下面三件事:

  1. 经过反射创立方针 Activity 方针。
  2. 调用 attach 办法树立 Activity 与 Context 之间的联络,创立 PhoneWindow 方针,并与 Activity 进行相关操作。
  3. 经过 Instrumentation 终究调用 Activity 的 onCreate 办法。

Instrumentation 的 callActivityOnCreate

    public void callActivityOnCreate(Activity activity, Bundle icicle) {
        prePerformCreate(activity);
        activity.performCreate(icicle);
        postPerformCreate(activity);
    }

performCreate 中会调用 Activity 的 onCreate。Activity 的发动就完结了。

至此,方针 Activity 现已被成功创立并履行生命周期办法。

总结

不得不说,Android 每一个版别之前源码都是有一些变动的,今天咱们剖析了依据 android-30 版别的Activity 的发动的完结流程。这一进程首要触及 4 个进程间的通讯进程:

  • 首要 Launcher 进程经过 Binder 调用 ActivityTaskManagerService 的 startActivity 办法。
  • 然后 ActivityTaskManagerService 经过一系列的核算结构方针 Intent,然后在 ActivityStack 与 ActivityStackSupervisor 中处理 Task 和 Activity 的入栈操作。
  • ActivityTaskManagerService 经过 socket 调用向 Zygote 发送启用使用进程来达到创立使用进程的意图。
  • 终究 ActivityTaskManagerService 经过 Binder 机制,调用方针进程中 ApplicationThread 的办法来创立并履行 Activity 生命周期办法,实际上 ApplicationThread 是 ActivityThread 的一个内部类,它的履行终究都调用到了 ActivityThread 中的相应办法。