关于 Android 客户端开发者来说,Activity 是咱们再了解不过的一个组件了。它是 Android 四大组件之一,是一个用于直接与用户交互的展示型 UI 组件。在开发进程中,发动并创立一个 Activity 流程十分简略,而在体系底层实际上做了大量的工作,之所以运用这么简略,得益于体系底层关于 Activity 的杰出封装。本篇内容咱们着重来剖析一下 Framework 层 Activity 的发动与创立的进程。

一、前语

在 《不得不说的 Android Binder 机制与 AIDL》这篇文章中咱们了解了经过怎样经过 Binder 与 AIDL 进行跨进程通信,在另一篇文章 《反思 Android 音讯机制的规划与完结》深入讨论了 Handler 音讯机制的完结原理。这两篇文章,尤其是经过 Binder 与 AIDL 跨进程通信这块内容是了解本篇文章的基础,假如现在还不了解的同学建议先去阅览这两篇文章。

在平时的开发中,发动一个新的 Activity 只需求在当时 Activity 中调用startActivity办法,并传入一个Intent 即可,例如,从 MainActivity 发动一个 TestActivity 代码如下:

Intent intent = new Intent(this, TestActivity.class);
startActivity(intent);

两行看似简略的代码,实际上阅历了与 system_service 进程的数次互相调用,才成功发动了一个 Activity。为方便了解,后文中咱们把发动 Activity 的进程称为客户端,把 system_server 进程称为服务端。

二、客户端的调用流程

startActivity 的操作是由客户端发起的,因而当时的代码履行在客户端进程中。追进startActivity即可看到如下源码

// frameworks/base/core/java/android/app/Activity.java
    ActivityThread mMainThread;
    @Override
    public void startActivity(Intent intent) {
        this.startActivity(intent, null);
    }
    @Override
    public void startActivity(Intent intent, @Nullable Bundle options) {
        getAutofillClientController().onStartActivity(intent, mIntent);
        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,
            @Nullable Bundle options) {
        if (mParent == null) {
            options = transferSpringboardActivityOptions(options);
            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());
            }
            // ...
        } else {
            // ...
        }
    }

能够看到,startActivity 办法终究会调用 startActivityForResult 办法,这个办法的中心代码是经过 Instrumentation 调用了 execStartActivity。而 execStartActivity 办法中的第二个参数为 mMainThread.getApplicationThread(),这儿的 mMainThread 即为 ActivityThread,经过 ActivityThread 获取到了 ApplicationThread,ApplicationThread 是一个 Binder 类,这个类终究会被传到服务端,在服务端作为客户端的代理来调用客户端的代码,关于这个类后文还会剖析。

持续跟进 Instrumentation 的 execStartActivity 办法,代码如下:

// frameworks/base/core/java/android/app/Instrumentation.java
    public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {
        IApplicationThread whoThread = (IApplicationThread) contextThread;
        Uri referrer = target != null ? target.onProvideReferrer() : null;
        if (referrer != null) {
            intent.putExtra(Intent.EXTRA_REFERRER, referrer);
        }
        // ...
        try {
            intent.migrateExtraStreamToClipData(who);
            intent.prepareToLeaveProcess(who);
            // 经过 ActivityTaskManager 获取 Service 来发动 Activity
            int result = ActivityTaskManager.getService().startActivity(whoThread,
                    who.getOpPackageName(), who.getAttributionTag(), intent,
                    intent.resolveTypeIfNeeded(who.getContentResolver()), token,
                    target != null ? target.mEmbeddedID : null, requestCode, 0, null, options);
            notifyStartActivityResult(result, options);
            // 检查 Activity 的发动成果,例如是否在 AndroidManifest 文件中注册,没有则抛出反常
            checkStartActivityResult(result, intent);
        } catch (RemoteException e) {
            throw new RuntimeException("Failure from system", e);
        }
        return null;
    }

上述办法的中心代码是经过 ActivityTaskManager 获取到了一个 Service,具体是一个什么 Service 这儿并不能看出来,咱们持续跟进 ActivityTaskManager 的 getService 能够看到如下代码:

// frameworks/base/core/java/android/app/ActivityTaskManager.java
    public static IActivityTaskManager getService() {
        return IActivityTaskManagerSingleton.get();
    }
    @UnsupportedAppUsage(trackingBug = 129726065)
    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);
                }
            };

这儿能够看到 getService 获取到的是一个 IActivityTaskManager,IActivityTaskManager 是什么呢?经过查找源码,发现它其实是一个 AIDL 类,目录为: frameworks/base/core/java/android/app/IActivityTaskManager.aidl,因而,IActivityTaskManager#startActivity 在这儿肯定是一个跨进程的操作,到这儿代码就进入了服务端进程,即 system_server 进程。

三、服务端的调用流程

经过上一小节的剖析,代码现已履行到了 system_server 进程,那在 system_server 进程中调用的是哪个类呢?了解 AIDL 的同学应该清楚,在编译完代码后 IActivityTaskManager 这个 AIDL 文件会生成一个 IActivityTaskManager.Stub 类,这个类承继自 Binder, 并且会有一个名为 startActivity 的笼统办法。因而接下来咱们需求找到哪个类承继了 IActivityTaskManager.Stub 即可,经过大局查找咱们发现 ActivityTaskManagerService 承继了 IActivityTaskManager.Stub,其部分源码如下:

// frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
    // ...
    private ActivityStartController mActivityStartController;
   @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());
    }
   @Override
    public int startActivityAsUser(IApplicationThread caller, String callingPackage,
            String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
            String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
            Bundle bOptions, int userId) {
        return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
                resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
                true /*validateIncomingUser*/);
    }
    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) {
        // ... 省掉装备项获取与校验
        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(opts)
                .setUserId(userId)
                .execute();
    } 
}

能够看到,在这个类中 startActivity 终究调用了 startActivityAsUser 办法,这个办法中的代码也比较简略,便是经过 getActivityStartController().obtainStarter 来装备相关参数,并终究履行 execute

getActivityStartController() 获取到的是一个 ActivityStartController 目标,如下:

     ActivityStartController getActivityStartController() {
        return mActivityStartController;
    }

接着调用了 ActivityStartController 的 obtainStarter,代码如下:

/// ActivityStartController
ActivityStarter obtainStarter(Intent intent, String reason) {
    return mFactory.obtain().setIntent(intent).setReason(reason);
}

obtainStarter 回来的是一个 ActivityStarter 目标,疏忽相关参数的装备,咱们直接看 ActivityStarter 的 execute 办法,源码如下:

// frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java
private final ActivityTaskSupervisor mSupervisor;
int execute() {
        try {
            onExecutionStarted();
            // ... 
            int res;
            synchronized (mService.mGlobalLock) {
                // ...
                res = executeRequest(mRequest);
                // ...
                }
                return getExternalResult(res);
            }
        } finally {
            onExecutionComplete();
        }
    }

execute 办法又调用了 executeRequest 办法,源码如下:

// frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java
private int executeRequest(Request request) {
        // ... 省掉参数初始化及权限校验
        final ActivityRecord r = new ActivityRecord.Builder(mService)
                .setCaller(callerApp)
                .setLaunchedFromPid(callingPid)
                .setLaunchedFromUid(callingUid)
                .setLaunchedFromPackage(callingPackage)
                .setLaunchedFromFeature(callingFeatureId)
                .setIntent(intent)
                .setResolvedType(resolvedType)
                .setActivityInfo(aInfo)
                .setConfiguration(mService.getGlobalConfiguration())
                .setResultTo(resultRecord)
                .setResultWho(resultWho)
                .setRequestCode(requestCode)
                .setComponentSpecified(request.componentSpecified)
                .setRootVoiceInteraction(voiceSession != null)
                .setActivityOptions(checkedOptions)
                .setSourceRecord(sourceRecord)
                .build();
        // ...
        mLastStartActivityResult = startActivityUnchecked(r, sourceRecord, voiceSession,
                request.voiceInteractor, startFlags, true /* doResume */, checkedOptions,
                inTask, inTaskFragment, restrictedBgActivity, intentGrants);
        if (request.outActivity != null) {
            request.outActivity[0] = mLastStartActivityRecord;
        }
        return mLastStartActivityResult;
    }

executeRequest 办法中的中心是实例化了 ActivityRecord,并调用 startActivityUnchecked,

// frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, Task inTask,
            TaskFragment inTaskFragment, boolean restrictedBgActivity,
            NeededUriGrants intentGrants) {
        try {
            mService.deferWindowLayout();
            try {
                result = startActivityInner(r, sourceRecord, voiceSession, voiceInteractor,
                        startFlags, doResume, options, inTask, inTaskFragment, restrictedBgActivity,
                        intentGrants);
            } finally {
                // ...
            }
        } finally {
            mService.continueWindowLayout();
        }
        postStartActivityProcessing(r, result, startedActivityRootTask);
        return result;
    }`java

startActivityUnchecked 办法中又调用了 startActivityInner,源码如下:

// frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java
private final RootWindowContainer mRootWindowContainer;
int startActivityInner(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, Task inTask,
            TaskFragment inTaskFragment, boolean restrictedBgActivity,
            NeededUriGrants intentGrants) {
        setInitialState(r, options, inTask, inTaskFragment, doResume, startFlags, sourceRecord,
                voiceSession, voiceInteractor, restrictedBgActivity);
        // 处理 Intent 中携带的 flags
        computeLaunchingTaskFlags();
        // 获取发动 Activity 的使命栈,这儿即获取 MainActivity 地点的使命栈 
        computeSourceRootTask();
        // ...
        // 查找可用的使命栈
        final Task reusedTask = getReusableTask();
        // ...
        // 假如 reusedTask 不空,则运用 reusedTask 使命栈,否则寻找目标使命栈
        final Task targetTask = reusedTask != null ? reusedTask : computeTargetTask();
        // 目标使命栈为空,则标记为运用新使命栈,需求新建使命栈
        final boolean newTask = targetTask == null;
        mTargetTask = targetTask;
        computeLaunchParams(r, sourceRecord, targetTask);
        if (newTask) {
            // 创立一个新的使命栈
            final Task taskToAffiliate = (mLaunchTaskBehind && mSourceRecord != null)
                    ? mSourceRecord.getTask() : null;
            // 将 Activity 放入新建的使命栈        
            setNewTask(taskToAffiliate);
        } else if (mAddingToTask) {
            // 加入已有的使命栈
            addOrReparentStartingActivity(targetTask, "adding to task");
        }
        // ...
        if (mDoResume) {
                // ...
                mRootWindowContainer.resumeFocusedTasksTopActivities(
                        mTargetRootTask, mStartActivity, mOptions, mTransientLaunch);
            }
        }
        return START_SUCCESS;
    }

startActivityInner 办法中的代码比较杂乱。经过了简化处理后,能够看到这个办法里首要是处理使命栈相关的逻辑,假如找到可用的使命栈则直接运用这个使命栈,假如没有找到,则新建一个使命栈。 在完结使命栈的处理之后经过mRootWindowContainer.resumeFocusedTasksTopActivities持续 Activity 的发动流程,这儿的 mRootWindowContainer 是 RootWindowContainer 的实例,resumeFocusedTasksTopActivities 代码如下:

// frameworks/base/services/core/java/com/android/server/wm/RootWindowContainer.java
 boolean resumeFocusedTasksTopActivities(
            Task targetRootTask, ActivityRecord target, ActivityOptions targetOptions,
            boolean deferPause) {
        // ...
        boolean result = false;
        if (targetRootTask != null && (targetRootTask.isTopRootTaskInDisplayArea()
                || getTopDisplayFocusedRootTask() == targetRootTask)) {
            result = targetRootTask.resumeTopActivityUncheckedLocked(target, targetOptions,deferPause);
        }
        // ...
        return result;
    }

这个办法中将发动相关的代码交给了 Task 的 resumeTopActivityUncheckedLocked 办法。代码如下:

frameworks/base/services/core/java/com/android/server/wm/Task.java
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options,
            boolean deferPause) {
        // ...
        boolean someActivityResumed = false;
        try {
            // Protect against recursion.
            mInResumeTopActivity = true;
            if (isLeafTask()) {
                if (isFocusableAndVisible()) {
                    someActivityResumed = resumeTopActivityInnerLocked(prev, options, deferPause);
                }
            } else {
                       // ...
                   }
            }
        // ...
        return someActivityResumed;
    }
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
        return resumeTopActivityUncheckedLocked(prev, options, false /* skipPause */);
    }
    @GuardedBy("mService")
    private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options,
            boolean deferPause) {
        if (!mAtmService.isBooting() && !mAtmService.isBooted()) {
            // Not ready yet!
            return false;
        }
        // 使命栈栈顶正在运转的 Activity 
        final ActivityRecord topActivity = topRunningActivity(true /* focusableOnly */);
        if (topActivity == null) {
            // 空使命栈 There are no activities left in this task, let's look somewhere else.
            return resumeNextFocusableActivityWhenRootTaskIsEmpty(prev, options);
        }
        final boolean[] resumed = new boolean[1];
        final TaskFragment topFragment = topActivity.getTaskFragment();
        resumed[0] = topFragment.resumeTopActivity(prev, options, deferPause);
        // ...
        return resumed[0];
    }

在 Task 的 resumeTopActivityUncheckedLocked 办法中从而又调用了resumeTopActivityUncheckedLocked,在 resumeTopActivityInnerLocked 中经过 TaskFragment 调用了 resumeTopActivity,接着来看 TaskFragment 中的完结。

frameworks/base/services/core/java/com/android/server/wm/TaskFragment.java
final ActivityTaskSupervisor mTaskSupervisor;
final boolean resumeTopActivity(ActivityRecord prev, ActivityOptions options,
            boolean deferPause) {
        ActivityRecord next = topRunningActivity(true /* focusableOnly */);
         // ...
         if (mResumedActivity != null) {
             // 暂停栈顶的Activity
            pausing |= startPausing(mTaskSupervisor.mUserLeaving, false /* uiSleeping */, next, "resumeTopActivity");
        }
        // ... 
        // 要发动的 Activity 已存在,且不需求重新创立,例如设置了 singleTask 或 singleTop发动形式
        if (next.attachedToProcess()) {
            // ...
            ActivityRecord lastResumedActivity =
                    lastFocusedRootTask == null ? null
                            : lastFocusedRootTask.getTopResumedActivity();
            final ActivityRecord.State lastState = next.getState();
            mAtmService.updateCpuStats();
            next.setState(RESUMED, "resumeTopActivity");
            // Have the window manager re-evaluate the orientation of
            // the screen based on the new activity order.
            boolean notUpdated = true;
            // ...
            try {
                // 敞开一个业务
                final ClientTransaction transaction =
                        ClientTransaction.obtain(next.app.getThread(), next.token);
                 // ...
                if (next.newIntents != null) {
                    // 增加 onNewIntent 的 callback ,终究会在APP端履行 onNewIntent()
                    transaction.addCallback(
                            NewIntentItem.obtain(next.newIntents, true /* resume */));
                }
                // ...
                // 设置 Activity 终究的生命周期状况为 Resume
                transaction.setLifecycleStateRequest(
                        ResumeActivityItem.obtain(next.app.getReportedProcState(),
                                dc.isNextTransitionForward()));
                // Flag1:开端履行业务                
                mAtmService.getLifecycleManager().scheduleTransaction(transaction);
            } catch (Exception e) {
                // ...
                // Resume 反常,重新发动
                mTaskSupervisor.startSpecificActivity(next, true, false);
                return true;
            }
           // ...
        } else {
            // ...
            // 发动 Activity
            mTaskSupervisor.startSpecificActivity(next, true, true);
        }
        return true;
    }

resumeTopActivity 办法中首要有两部分内容。

  • next.attachedToProcess() 为 true,即要发动的这个 Activity 现已存在,并且设置了像“singleInstance” 的发动形式,无需重新创立 Activity 的情况下,则先经过 ClientTransaction 增加了一个 NewIntentItem 的 callback,接下来经过 setLifecycleStateRequest 设置了一个 ResumeActivityItem 目标。
  • next.attachedToProcess() 为 false ,则持续履行 Activity 的发动流程

榜首部分中的 ClientTransaction 是什么? scheduleTransaction 又是做了什么?这儿先不做讨论,留一个Flag,后边再来剖析。

接着持续看主线流程,在 next.attachedToProcess() 回来 false 之后,经过 ActivityTaskSupervisor 调用了 startSpecificActivity,这儿是 Activity 正常发动的流程,检查 startSpecificActivity 源码如下:

frameworks/base/services/core/java/com/android/server/wm/ActivityTaskSupervisor.java
    void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) {
        // Is this activity's application already running?
        final WindowProcessController wpc =
                mService.getProcessController(r.processName, r.info.applicationInfo.uid);
        boolean knownToBeDead = false;
        if (wpc != null && wpc.hasThread()) {
            try {
                realStartActivityLocked(r, wpc, andResume, checkConfig);
                return;
            } catch (RemoteException e) {
               // ...
            }
            // ...
        }
        // ...
    }
   boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
            boolean andResume, boolean checkConfig) throws RemoteException {
        // ...
        final Task task = r.getTask();
        final Task rootTask = task.getRootTask();
        try {
                // ...
                // 创立发动 Activity 的业务
                final ClientTransaction clientTransaction = ClientTransaction.obtain(
                        proc.getThread(), r.token);
                final boolean isTransitionForward = r.isTransitionForward();
                final IBinder fragmentToken = r.getTaskFragment().getFragmentToken();
                // 增加发动 Activity 的 callback,履行launchActivity
                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.getFilteredReferrer(r.launchedFromPackage), task.voiceInteractor,
                        proc.getReportedProcState(), r.getSavedState(), r.getPersistentSavedState(),
                        results, newIntents, r.takeOptions(), isTransitionForward,
                        proc.createProfilerInfoIfNeeded(), r.assistToken, activityClientController,
                        r.shareableActivityToken, r.getLaunchedFromBubble(), fragmentToken));
                // Activity 发动后终究的生命周期状况
                final ActivityLifecycleItem lifecycleItem;
                if (andResume) {
                    // 将终究生命周期设置为 Resume 状况
                    lifecycleItem = ResumeActivityItem.obtain(isTransitionForward);
                } else {
                    // 将终究生命周期设置为 Pause 状况
                    lifecycleItem = PauseActivityItem.obtain();
                }
                // 设置 Activity 发动后终究的生命周期状况
                clientTransaction.setLifecycleStateRequest(lifecycleItem);
                // 敞开业务
                mService.getLifecycleManager().scheduleTransaction(clientTransaction);
               // ...
            } catch (RemoteException e) {
                // ...
            }
        } finally {
            // ...
        }
        // ...
        return true;
    }

startSpecificActivity 办法中最中心的逻辑是调用了 realStartActivityLocked ,这个办法中同样是获取了一个 ClientTransaction 实例,并调用了它的 addCallback 办法,与上边不同的是,这儿增加了一个 LaunchActivityItem 实例。

这儿与上边 Flag 处的代码逻辑是相同,仅仅增加的 callback 不同,那 ClientTransaction 是什么?它与 Activity 的发动又有什么关系呢?

1. ClientTransaction

ClientTransaction 是包含了一系列要履行的业务项的业务。咱们能够经过调用它的 addCallback办法来增加一个业务项,你也能够屡次调用来增加多个业务项。addCallback 接收的参数类型为 ClientTransactionItem,而这个 ClientTransactionItem 有多个子类,例如上边现已出现过的 NewIntentItem、LaunchActivityItem 等都是其子类。

另外能够经过 ClientTransactionItem 的 setLifecycleStateRequest 办法设置 Activity 履行完后终究的生命周期状况,其参数的类型为 ActivityLifecycleItem。ActivityLifecycleItem 也是承继自 ClientTransactionItem。同时,ActivityLifecycleItem 也有多个子类,它的每个子类都对应了 Activity 的一个生命周期事件。

在完结 callback 与 lifeCycleStateRequest 的设置之后,便经过调用 mService.getLifecycleManager().scheduleTransaction(clientTransaction)办法敞开业务项的履行。

这儿的 mService.getLifecycleManager() 获取到的是什么呢?盯梢 ActivityTaskManagerService 源码咱们能够找到 getLifecycleManager 的代码如下:

// frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
    private final ClientLifecycleManager mLifecycleManager;
    ClientLifecycleManager getLifecycleManager() {
        return mLifecycleManager;
    }

能够看到,getLifecycleManager 回来了一个 ClientLifecycleManager 的实例,并调用了 scheduleTransaction 办法,代码如下:

// frameworks/base/services/core/java/com/android/server/wm/ClientLifecycleManager.java
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
        final IApplicationThread client = transaction.getClient();
        transaction.schedule();
        // ...
    }

上述办法的中心代码是调用了 ClientTransaction 的 schedule 办法,schedule 办法源码如下:

 // frameworks/base/core/java/android/app/servertransaction/ClientTransaction.java
 private IApplicationThread mClient;
 public void schedule() throws RemoteException {
         mClient.scheduleTransaction(this);
    }

在 schedule 办法中经过 mClient 调用了 scheduleTransaction, 这儿的 mClient 即为 IApplicationThread,也便是咱们在第二章中说到的客户端的 Binder。这个参数是在实例化 ClientTransaction 时传进来的,IApplicationThread 是一个AIDL 类,那么经过编译后它会生成一个 IApplicationThread.Stub 类,上文中说到的 ActivityThread#ApplicationThread 便是承继了IApplicationThread.Stub。

// frameworks/base/core/java/android/app/ActivityThread#ApplicationThread 
private class ApplicationThread extends IApplicationThread.Stub {
    // ...
}

已然咱们现已知道了 IApplicationThread 是客户端 Binder 在服务端的代理, 那么这儿实际上是便是调用了客户端 ApplicationThread 中的 scheduleTransaction 办法。

至此,代码终究又回到了客户端的 ApplicationThread 中。但是,关于 ClientTransaction 的剖析到这儿还未完毕。能够看到的是,此刻的代码又经过 scheduleTransaction 办法回到了客户端,并且将 ClientTransaction 作为参数传了过去。那么,ClientTransaction 的履行逻辑实际上在客户端中履行的。

四、再探客户端的调用流程

经过 Binder IPC,代码的调用流程又回到了客户端,来看 ApplicationThread 中 scheduleTransaction 办法的完结,源码如下:

// frameworks/base/core/java/android/app/ActivityThread#ApplicationThread
    @Override
    public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
        ActivityThread.this.scheduleTransaction(transaction);
    }

这个办法中又调用了 ActivityThread 的 scheduleTransaction 。而 scheduleTransaction 的源码在ActivityThread 的父类 ClientTransactionHandler 中, 如下:

// frameworks/base/core/java/android/app/ClientTransactionHandler.java
    void scheduleTransaction(ClientTransaction transaction) {
        transaction.preExecute(this);
        sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
    }

这儿将 transaction 作为参数调用了 sendMessage 办法。sendMessage 办法源码如下:


    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) {
        Message msg = Message.obtain();
        msg.what = what;
        msg.obj = obj;
        msg.arg1 = arg1;
        msg.arg2 = arg2;
        if (async) {
            // 设置异步音讯,会优先履行
            msg.setAsynchronous(true);
        }
        mH.sendMessage(msg);
    }

能够看到,这儿终究将 ClientTransaction 与 EXECUTE_TRANSACTION 打包成一个 Message ,并且将这个 Message 设置成了异步音讯,终究经过 mH 发送了出去,这儿的 mH 是一个承继自 Handler 的 H 类,位于 ActivityThread 类的内部。

Message 被设置为异步音讯后具有优先履行权,因为 Activity 的发动涉及到 Activity 的创立以及生命周期的调用,一切这儿发送出来的 Message 不该该被其他 Message 阻塞,否则肯定会影响到 Activity 的发动,造成卡顿问题。具体剖析能够参见 《反思 Android 音讯机制的规划与完结》 这篇文章。

接下来看一下在 H 类的内部是怎样处理这条音讯的,咱们查找 EXECUTE_TRANSACTION 能够看到如下代码:

// frameworks/base/core/java/android/app/ActivityThread#H
public void handleMessage(Message msg) {
    switch (msg.what) {
    case EXECUTE_TRANSACTION:
            final ClientTransaction transaction = (ClientTransaction) msg.obj;
            mTransactionExecutor.execute(transaction);
            // ...
             break;
    }
}

这儿的代码很简略,经过 Message 拿到 ClientTransaction 后,然后经过 TransactionExecutor 的 execute 办法来履行 ClientTransaction。

在上一章中,咱们仅仅对 ClientTransaction 做了简略的介绍。虽然 ClientTransaction 的实例化是在服务端,但其履行流程却是在客户端。看一下 TransactionExecutor 中 execute 源码:

// frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java
public void execute(ClientTransaction transaction) {
       // ...
        // 履行 callback
        executeCallbacks(transaction);
        // 履行 lifecycleState
        executeLifecycleState(transaction);
        mPendingActions.clear();
    }   

这个办法里的履行逻辑能够分为两部分:

  • 经过 executeCallbacks 办法履行一切被增加进来的 ClientTransactionItem
  • 经过 executeLifecycleState 办法将 Activity 的生命周期履行到指定的状况

1. executeCallbacks 办法剖析

executeCallbacks 办法中的逻辑比较简略,其源码如下:


public void executeCallbacks(ClientTransaction transaction) {
        // ...
        final int size = callbacks.size();
        for (int i = 0; i < size; ++i) {
            // ...
            final ClientTransactionItem item = callbacks.get(i);
            item.execute(mTransactionHandler, token, mPendingActions);
            // ...
            cycleToPath(r, postExecutionState, shouldExcludeLastTransition, transaction);
            }
        }
    }

在 executeCallbacks 中遍历了一切的 ClientTransactionItem 并履行了 ClientTransactionItem 的 execute 办法。上一章咱们剖析了,当 Activity 正常发动时,经过 addCallback 增加的是一个 LaunchActivityItem 的实例。以此为例,这儿就会首先履行 LaunchActivityItem 的 execute 办法,从而履行 Activity 的实例化及 onCreate 生命周期的调用。这块源码留作后边再来剖析。

2. ClientTransactionItem

咱们上文说到过 ClientTransactionItem 有多个完结类,这些完结类对应了 Activity 中不同的履行流程。例如在 Activity 发动时假如不需求重新创立 Activity ,则会经过 addCallback 增加了一个 NewIntentItem 来履行 Activity 的 onNewIntennt 办法。而当需求重新创立 Activity 时,则传入的是一个 LaunchActivityItem,用来创立并发动Activity。

ClientTransactionItem 的一切子类或相关类均在 frameworks/base/core/java/android/app/servertransaction/ 目录下,如下图所示:

基于 Android 13 的 Activity 启动流程分析

上文中说到的 ActivityLifecycleItem 承继自 ClientTransactionItem ,且其子类均为 Activity 生命周相关的完结,例如,StartActivityItem、ResumeActivityItem、DestroyActivityItem 等。清楚明了的是,这儿将 Activity 的生命周期以及其它相关办法以面向目标的思维封装成了一个个的目标来履行。比较早些年的 Android 版本代码,一切生命周期以及相关办法都经过 Handler 的 sendMessage 的办法发送出来,这种面向目标的思维的逻辑愈加明晰,且代码更容易维护。

3. executeLifecycleState 办法剖析

接着来看 executeCallbacks 中的 executeLifecycleState 办法,前面说到过,这儿会将 Activity 履行到指定的生命周期状况。上边的代码中咱们看到在 Activity 发动时,setLifecycleStateRequest 设置的是一个 ResumeActivityItem,代码如下:

   // 设置 Activity 终究的生命周期状况为 Resume
   transaction.setLifecycleStateRequest(
          ResumeActivityItem.obtain(next.app.getReportedProcState(),
                 dc.isNextTransitionForward()));

设置了 ResumeActivityItem后,接下来的代码会怎样履行呢?来看 executeLifecycleState 办法的源码:

   private void executeLifecycleState(ClientTransaction transaction) {
        final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
        // ...
        // 第二个参数为履行完时的生命周状况
        cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */, transaction);
        // Execute the final transition with proper parameters.
        lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
        lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
    }

这段代码的关键点在于 cycleToPath 。同时,经过 lifecycleItem.getTargetState() 作为完毕时的生命周期状况。因为此刻设置的是一个 ResumeActivityItem,它的 getTargetState 回来的是一个 ON_RESUME 的值,代码如下:

// frameworks/base/core/java/android/app/servertransaction/ResumeActivityItem.java
    @Override
    public int getTargetState() {
        return ON_RESUME;
    }
    @Retention(RetentionPolicy.SOURCE)
    public @interface LifecycleState{}
    public static final int UNDEFINED = -1;
    public static final int PRE_ON_CREATE = 0;
    public static final int ON_CREATE = 1;
    public static final int ON_START = 2;
    public static final int ON_RESUME = 3;
    public static final int ON_PAUSE = 4;
    public static final int ON_STOP = 5;
    public static final int ON_DESTROY = 6;
    public static final int ON_RESTART = 7;

能够看到 ON_RESUME 的值为 3。接着来看 cycleToPath 源码:

private void cycleToPath(ActivityClientRecord r, int finish, boolean excludeLastState,
            ClientTransaction transaction) {
        // 获取当时 Activity 的生命周期状况,即开端时的状况    
        final int start = r.getLifecycleState();
        // 获取要履行的生命周期数组
        final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
        // 按次序履行 Activity 的生命周期
        performLifecycleSequence(r, path, transaction);
    }

在这个办法中,首先获取了当时 Activity 生命周期状况,即开端履行 getLifecyclePath 时 Activity 的生命周期状况,因为 executeLifecycleState 办法是在 executeCallback 之后履行的,上面咱们现已说到此刻的 Activity 现已履行完了创立流程,并履行过了 onCreate 的生命周期。因而,这儿的 start 应该是 ON_CREATE 状况,ON_CREATE 的值为 1。

那么接下来,这儿的关键点就在于 getLifecyclePath 做了什么。咱们看一下源码:

// frameworks/base/core/java/android/app/servertransaction/TransactionExecutorHelper.java
public IntArray getLifecyclePath(int start, int finish, boolean excludeLastState) {
        if (start == UNDEFINED || finish == UNDEFINED) {
            throw new IllegalArgumentException("Can't resolve lifecycle path for undefined state");
        }
        if (start == ON_RESTART || finish == ON_RESTART) {
            throw new IllegalArgumentException(
                    "Can't start or finish in intermittent RESTART state");
        }
        if (finish == PRE_ON_CREATE && start != finish) {
            throw new IllegalArgumentException("Can only start in pre-onCreate state");
        }
        mLifecycleSequence.clear();
        // Activity 发动 时,履行到这儿的 start 状况为 ON_CREATE,完毕状况为 ON_RESUME
        if (finish >= start) {
            if (start == ON_START && finish == ON_STOP) {
                // A case when we from start to stop state soon, we don't need to go
                // through the resumed, paused state.
                mLifecycleSequence.add(ON_STOP);
            } else {
                // 会走到这儿的逻辑,将 ON_START 与 ON_RESUME 增加到数组
                for (int i = start + 1; i <= finish; i++) {
                    mLifecycleSequence.add(i);
                }
            }
        } else { // finish < start, can't just cycle down
            if (start == ON_PAUSE && finish == ON_RESUME) {
                // Special case when we can just directly go to resumed state.
                mLifecycleSequence.add(ON_RESUME);
            } else if (start <= ON_STOP && finish >= ON_START) {
                // Restart and go to required state.
                // Go to stopped state first.
                for (int i = start + 1; i <= ON_STOP; i++) {
                    mLifecycleSequence.add(i);
                }
                // Restart
                mLifecycleSequence.add(ON_RESTART);
                // Go to required state
                for (int i = ON_START; i <= finish; i++) {
                    mLifecycleSequence.add(i);
                }
            } else {
                // Relaunch and go to required state
                // Go to destroyed state first.
                for (int i = start + 1; i <= ON_DESTROY; i++) {
                    mLifecycleSequence.add(i);
                }
                // Go to required state
                for (int i = ON_CREATE; i <= finish; i++) {
                    mLifecycleSequence.add(i);
                }
            }
        }
        // Remove last transition in case we want to perform it with some specific params.
        if (excludeLastState && mLifecycleSequence.size() != 0) {
            mLifecycleSequence.remove(mLifecycleSequence.size() - 1);
        }
        return mLifecycleSequence;
    }

根据上边剖析,此刻的 start 为 ON_CREATE(值为 1),而 finish 的值为 ON_RESUME(值为 2)。因而,履行完 getLifecyclePath 后,会得到一个包含了 ON_START 与 ON_RESUME 的数组。

接下来看performLifecycleSequence 中的代码:

    /** Transition the client through previously initialized state sequence. */
    private void performLifecycleSequence(ActivityClientRecord r, IntArray path,
            ClientTransaction transaction) {
        final int size = path.size();
        // 遍历数组,履行 Activity 的生命周
        for (int i = 0, state; i < size; i++) {
            state = path.get(i);
            switch (state) {
                case ON_CREATE:
                    mTransactionHandler.handleLaunchActivity(r, mPendingActions,
                            null /* customIntent */);
                    break;
                case ON_START:
                    mTransactionHandler.handleStartActivity(r, mPendingActions,
                            null /* activityOptions */);
                    break;
                case ON_RESUME:
                    mTransactionHandler.handleResumeActivity(r, false /* finalStateRequest */,
                            r.isForward, "LIFECYCLER_RESUME_ACTIVITY");
                    break;
                case ON_PAUSE:
                    mTransactionHandler.handlePauseActivity(r, false /* finished */,
                            false /* userLeaving */, 0 /* configChanges */,
                            false /* autoEnteringPip */, mPendingActions,
                            "LIFECYCLER_PAUSE_ACTIVITY");
                    break;
                case ON_STOP:
                    mTransactionHandler.handleStopActivity(r, 0 /* configChanges */,
                            mPendingActions, false /* finalStateRequest */,
                            "LIFECYCLER_STOP_ACTIVITY");
                    break;
                case ON_DESTROY:
                    mTransactionHandler.handleDestroyActivity(r, false /* finishing */,
                            0 /* configChanges */, false /* getNonConfigInstance */,
                            "performLifecycleSequence. cycling to:" + path.get(size - 1));
                    break;
                case ON_RESTART:
                    mTransactionHandler.performRestartActivity(r, false /* start */);
                    break;
                default:
                    throw new IllegalArgumentException("Unexpected lifecycle state: " + state);
            }
        }
    }

performLifecycleSequence 办法中则是遍历了这个数组。因为此刻的数组中有只要 ON_START 与 ON_RESUME 两个值,因而,这儿别离先后履行了 mTransactionHandler.handleStartActivitymTransactionHandler.handleResumeActivity,即调用了 ApplicationThread 的 handleStartActivity 与 handleResumeActivity 来履行 Activity 的 onStart 与 onResume 的生命周期。

五、Activity 的创立与生命周期的履行

经过前面几个章节的剖析咱们现已知道,Activity 的发动是在服务端经过增加一个 LaunchActivityItem 到 ClientTransaction 中完结的,然后经过 IApplicationThread 跨进程将 ClientTransaction 传到了客户端来履行的。客户端经过遍历 ClientTransaction 中的一切 ClientTransactionItem,并履行了它的 execute 办法从而来履行 Activity 的创立进程。那接下来咱们就来看一下 LaunchActivityItem 的 execute 办法调用后到底是怎样履行的。

// frameworks/base/core/java/android/app/servertransaction/LaunchActivityItem.java
@Override
    public void execute(ClientTransactionHandler client, IBinder token,
            PendingTransactionActions pendingActions) {
        ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
                mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
                mPendingResults, mPendingNewIntents, mActivityOptions, mIsForward, mProfilerInfo,
                client, mAssistToken, mShareableActivityToken, mLaunchedFromBubble,
                mTaskFragmentToken);
        client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
    }

LaunchActivityItem 的 execute 办法调用了 ClientTransactionHandler 的 handleLaunchActivity,而这儿的 ClientTransactionHandler 便是 ActivityThread。 ActivityThread 中 handleLaunchActivity 的源码如下:

// frameworks/base/core/java/android/app/ActivityThread.java
public Activity handleLaunchActivity(ActivityClientRecord r,
            PendingTransactionActions pendingActions, Intent customIntent) {
        // If we are getting ready to gc after going to the background, well
        // we are back active so skip it.
        unscheduleGcIdler();
        mSomeActivitiesChanged = true;
        // ...
        // 初始化 WindowManagerGlobal
        WindowManagerGlobal.initialize();
        // 调用 performLaunchActivity 履行 Activity 的创立流程
        final Activity a = performLaunchActivity(r, customIntent);
        // ...
        return a;
    }

在 handleLaunchActivity 办法中首先去初始化了 WindowManagerGlobal,紧接着调用了 performLaunchActivity 并回来了一个 Activity 实例,那么 Activity 的实例化必定是在 performLaunchActivity 中完结的。

1. Activity 的实例化与 onCreate 的调用

看下 performLaunchActivity 的源码:

// frameworks/base/core/java/android/app/ActivityThread.java
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        ActivityInfo aInfo = r.activityInfo;
        // ...
        ContextImpl appContext = createBaseContextForActivity(r);
        Activity activity = null;
        try {
            // 在 Instrumentation 中经过反射实例化 Activity 
            java.lang.ClassLoader cl = appContext.getClassLoader();
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
            StrictMode.incrementExpectedActivityCount(activity.getClass());
            r.intent.setExtrasClassLoader(cl);
            r.intent.prepareToEnterProcess(isProtectedComponent(r.activityInfo),
                    appContext.getAttributionSource());
            if (r.state != null) {
                r.state.setClassLoader(cl);
            }
        } catch (Exception e) {
            if (!mInstrumentation.onException(activity, e)) {
                throw new RuntimeException(
                    "Unable to instantiate activity " + component
                    + ": " + e.toString(), e);
            }
        }
       // ... 省掉后半部分履行 Activity 生命周期的代码
        return activity;
    }

这个办法中的首要逻辑能够分为两部分,榜首部分是实例化 Activity;第二部分是履行 Activity 的 onCreate 的生命周期。因为代码比较长,这儿咱们只截取了榜首部分的代码。能够看到这儿经过 Instrumentation 的 newActivity 获取到一个 Activity 实例,newActivity 的参数传入了一个 ClassLoader 和 Activity 的 className。因而,这儿实例化 Activity 的进程一定是经过反射完结的。看代码:

    public Activity newActivity(Class<?> clazz, Context context,
            IBinder token, Application application, Intent intent, ActivityInfo info, 
            CharSequence title, Activity parent, String id,
            Object lastNonConfigurationInstance) throws InstantiationException,
            IllegalAccessException {
        Activity activity = (Activity)clazz.newInstance();
        ActivityThread aThread = null;
        // Activity.attach expects a non-null Application Object.
        if (application == null) {
            application = new Application();
        }
        activity.attach(context, aThread, this, token, 0 /* ident */, application, intent,
                info, title, parent, id,
                (Activity.NonConfigurationInstances)lastNonConfigurationInstance,
                new Configuration(), null /* referrer */, null /* voiceInteractor */,
                null /* window */, null /* activityCallback */, null /*assistToken*/,
                null /*shareableActivityToken*/);
        return activity;
    }

newActivity 中经过反射实例化了 Activity,接着调用了 Activity 的 attach 办法。

接下来看 performLaunchActivity 办法的后半部分的逻辑。在实例化了 Activity 之后是怎样调用 Activity 的 onCreate 生命周期的。

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        ActivityInfo aInfo = r.activityInfo;
        // ...
        try {
            // 获取 Application 
            Application app = r.packageInfo.makeApplicationInner(false, mInstrumentation);
            // ...
            if (activity != null) {
                CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
                Configuration config =
                        new Configuration(mConfigurationController.getCompatConfiguration());
                // ...
                // Activity resources must be initialized with the same loaders as the
                // application context.
                appContext.getResources().addLoaders(
                        app.getResources().getLoaders().toArray(new ResourcesLoader[0]));
                appContext.setOuterContext(activity);
                // 再次履行 Activity 的 attach 办法
                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);
                if (customIntent != null) {
                    activity.mIntent = customIntent;
                }
                r.lastNonConfigurationInstances = null;
                checkAndBlockForNetworkAccess();
                activity.mStartedActivity = false;
                int theme = r.activityInfo.getThemeResource();
                if (theme != 0) {
                    // 设置 Activity 主题
                    activity.setTheme(theme);
                }
                if (r.mActivityOptions != null) {
                    activity.mPendingOptions = r.mActivityOptions;
                    r.mActivityOptions = null;
                }
                activity.mLaunchedFromBubble = r.mLaunchedFromBubble;
                activity.mCalled = false;
                // Assigning the activity to the record before calling onCreate() allows
                // ActivityThread#getActivity() lookup for the callbacks triggered from
                // ActivityLifecycleCallbacks#onActivityCreated() or
                // ActivityLifecycleCallback#onActivityPostCreated().
                r.activity = activity;
                // 调用 Activity 的 onCreate 办法
                if (r.isPersistable()) {
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
                // ...
            }
            r.setState(ON_CREATE);
        } catch (SuperNotCalledException e) {
           // ...
        } 
        return activity;
    }

上述办法中首先获取 Activity 的 title 以及 Configuration 等相关参数,然后再次调用 Activity 的 attach 办法,并将这些参数传入。attach 办法中首要做了初始化 PhoneWindow 的一些操作,代码如下:

// frameworks/base/core/java/android/app/Activity.java
final void attach(Context context, ActivityThread aThread,
            Instrumentation instr, IBinder token, int ident,
            Application application, Intent intent, ActivityInfo info,
            CharSequence title, Activity parent, String id,
            NonConfigurationInstances lastNonConfigurationInstances,
            Configuration config, String referrer, IVoiceInteractor voiceInteractor,
            Window window, ActivityConfigCallback activityConfigCallback, IBinder assistToken,
            IBinder shareableActivityToken) {
        attachBaseContext(context);
        mFragments.attachHost(null /*parent*/);
        // 实例化 PhoneWindow,Activity 中持有 PhoneWindow
        mWindow = new PhoneWindow(this, window, activityConfigCallback);
        mWindow.setWindowControllerCallback(mWindowControllerCallback);
        // 将 Activity 本身设置到 PhoneWindow
        mWindow.setCallback(this);
        mWindow.setOnWindowDismissedCallback(this);
        mWindow.getLayoutInflater().setPrivateFactory(this);
        // ...
        // PhoneWindow 关联 WindowManager
        mWindow.setWindowManager(
                (WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
                mToken, mComponent.flattenToString(),
                (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
        if (mParent != null) {
            mWindow.setContainer(mParent.getWindow());
        }
        // Activity 中持有 WindowManager
        mWindowManager = mWindow.getWindowManager();
        mCurrentConfig = config;
        mWindow.setColorMode(info.colorMode);
        mWindow.setPreferMinimalPostProcessing(
                (info.flags & ActivityInfo.FLAG_PREFER_MINIMAL_POST_PROCESSING) != 0);
        getAutofillClientController().onActivityAttached(application);
        setContentCaptureOptions(application.getContentCaptureOptions());
    }

调用 attach 办法之后,接着经过 Instrumentation 履行了 Activity 的 performCreate 办法,代码如下:

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

而 Activity 的 performCreate 办法中终究会调用 Activity 的 onCreate办法。至此,咱们在 Activity 的 onCreate 办法中写的逻辑才会被调用。performCreate 办法的代码这儿就不再贴出,有兴趣的能够自行检查。

2. onStart 办法的履行

在第四章的第 3 小节中,中咱们现已剖析了创立完 Activity 后怎样履行后续的生命周期流程。咱们知道 onStart 是经过 ActivityThread 的 handleStartActivity 来履行的,其源码如下:

// frameworks/base/core/java/android/app/ActivityThread.java
public void handleStartActivity(ActivityClientRecord r,
            PendingTransactionActions pendingActions, ActivityOptions activityOptions) {
        final Activity activity = r.activity;
        if (!r.stopped) {
            throw new IllegalStateException("Can't start activity that is not stopped.");
        }
        if (r.activity.mFinished) {
            // TODO(lifecycler): How can this happen?
            return;
        }
        unscheduleGcIdler();
        if (activityOptions != null) {
            activity.mPendingOptions = activityOptions;
        }
        // 调用 Activity 的 performStart 从而履行 onStart
        activity.performStart("handleStartActivity");
        // 将生命周状况设置为 ON_START
        r.setState(ON_START);
       // ...
    }

handleStartActivity 的逻辑比较简略,便是调用了 Activity 的 performStart 办法,从而调用了 onStart 办法。这儿也不再贴出 performStart 办法的源码,感兴趣的同学自行检查。

3. onResume 办法的调用

onResume 办法是经过 ActivityThread 的 handleResumeActivity 来履行的,源码如下:

// frameworks/base/core/java/android/app/ActivityThread.java
public void handleResumeActivity(ActivityClientRecord r, boolean finalStateRequest,
            boolean isForward, boolean shouldSendCompatFakeFocus, String reason) {
        // If we are getting ready to gc after going to the background, well
        // we are back active so skip it.
        unscheduleGcIdler();
        mSomeActivitiesChanged = true;
        // TODO Push resumeArgs into the activity for consideration
        // skip below steps for double-resume and r.mFinish = true case.
        if (!performResumeActivity(r, finalStateRequest, reason)) {
            return;
        }
       // ... 省掉 Window 的增加逻辑
    }

handleResumeActivity 办法中的逻辑比较杂乱,但中心首要有两点:

  • 调用 performResumeActivity 履行 onResume 的生命周期
  • 将 DecorView 增加到 Window 中

上述代码中咱们省掉了 decorView 增加到 Window 部分的代码,后边再来剖析。先来看 performResumeActivity,其源码如下:

 public boolean performResumeActivity(ActivityClientRecord r, boolean finalStateRequest,
            String reason) {
        if (r.activity.mFinished) {
            // 假如 Activity 现已是finish状况,直接return false
            return false;
        }
        if (r.getLifecycleState() == ON_RESUME) {
            // 假如现已是 Resume 状况 直接return false,避免重复履行
            return false;
        }
        try {
           // ...
            // 履行 Activity 的 performResume 从而履行 onResume
            r.activity. performResume(r.startsNotResumed, reason);
            r.state = null;
            r.persistentState = null;
            // 设置 Activity 的状况 为 ON_RESUME
            r.setState(ON_RESUME);
            reportTopResumedActivityChanged(r, r.isTopResumedActivity, "topWhenResuming");
        } catch (Exception e) {
            if (!mInstrumentation.onException(r.activity, e)) {
                throw new RuntimeException("Unable to resume activity "
                        + r.intent.getComponent().toShortString() + ": " + e.toString(), e);
            }
        }
        return true;
    }

performResumeActivity 中先对 Activity 的状况进行了判别,假如状况契合,则会调用 Activity 的 performResume 办法,从而履行 Activity 的 onResume。performResume 办法的源码不再贴出。

在完结了 performResume 的调用后,performResumeActivity 办法中接着履行了将 DecorView 增加到 Window 的过。代码如下

// frameworks/base/core/java/android/app/ActivityThread.java
public void handleResumeActivity(ActivityClientRecord r, boolean finalStateRequest,
            boolean isForward, boolean shouldSendCompatFakeFocus, String reason) {
        // ...
        final Activity a = r.activity;
        if (r.window == null && !a.mFinished && willBeVisible) {
            // PhoneWindow
            r.window = r.activity.getWindow();
            // 获取 DecorView
            View decor = r.window.getDecorView();
            // 先设置 DecorView 不可见
            decor.setVisibility(View.INVISIBLE);
            // 获取 WindowManager
            ViewManager wm = a.getWindowManager();
            // 获取 Window 的特点参数
            WindowManager.LayoutParams l = r.window.getAttributes();
            a.mDecor = decor;
            l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
            l.softInputMode |= forwardBit;
            // ...
            if (a.mVisibleFromClient) {
                if (!a.mWindowAdded) {
                    a.mWindowAdded = true;
                    // 经过 WindowManager 将 DecorView增加到窗口
                    wm.addView(decor, l);
                } else {
                    // The activity will get a callback for this {@link LayoutParams} change
                    // earlier. However, at that time the decor will not be set (this is set
                    // in this method), so no action will be taken. This call ensures the
                    // callback occurs with the decor set.
                    a.onWindowAttributesChanged(l);
                }
            }
            // If the window has already been added, but during resume
            // we started another activity, then don't yet make the
            // window visible.
        } else if (!willBeVisible) {
            if (localLOGV) Slog.v(TAG, "Launch " + r + " mStartedActivity set");
            r.hideForNow = true;
        }
        // ...
    }

能够看到,上述办法的的中心是 wm.addView(decor, l) 这行代码,即经过 ViewManager 的 addView 办法将 DecorView 增加到了窗口中。窗口的增加进程会完结 DecorView 的布局、丈量与制作。当完结窗口的增加后 Activity 的 View 才被显示出来,且有了宽高。这也是为什么咱们在 onResume 中获取不到 View 宽高的原因。

另外需求注意到是,将 View 增加到 Window 的进程也是一个相当杂乱的进程,这个进程也屡次涉及到跨进程调用。这也是为什么在本文的开头说到 Activity 发动是一个数次跨进程调用的进程的原因。关于 Window 的增加进程,这儿就不再赘述了,后边会独自写一篇文章来详细剖析 Window 的增加。

六、总结

经过本篇文章咱们详细的了解了 Activity 的发动流程,虽然在开发中发动一个 Activity 只需求咱们调用一行代码,但经过追踪源码咱们发现 startActivity 办法的调用栈十分深,且中心涉及了两次跨进程的调用,假如不了解 Binder 与 AIDL 是比较难以读懂的。另外,因为 Activity 的发动进程比较杂乱,文章中不能八面玲珑,疏忽了很多支线逻辑,比方当发动 Activity 时,Activity 地点的进程不存在时的逻辑,本文章并没有去剖析,感兴趣的同学能够自行检查源码。