前语

Activity 类是 android 运用的要害组件,在日常开发中,肯定少不了组件。已然用了这么久,你知道他的发动流程?作为一个运用层开发者,大多数人或许觉得学习这些对日常开发或许没有太大协助。但是多了解一下 framework 的代码仍是很有必要的,了解体系组件机制,关于一些问题咱们也能快速的定位找到问题的地点点,并且在面试的时分也是一个加分项。

本文基于 Android 12 版本源码,从 startActivity 作为切入点,对整个发动流程进行剖析。

Activity 发动办法

发动一个 Activity,一般有两种情况,一种是在运用内部发动 Activity,另一种是 Launcher 发动。

  • 运用内发动

    经过 startActivity 来发动 Activity

  • Launcher 进程发动

    Launcher 便是咱们桌面程序,当体系开机后, Launcher 也随之被发动,然后将现已装置的 app 显现在桌面上,等到点击某一个 app 的时分就会 fock 一个新的进程,然后发动 Activity

这篇文章主要来看一下运用内发动 Activity 是一个怎样的流程

一,Activity -> ATMS

众所周知,一般情况下Activity 的发动办法有下面种:

  • startActivity(Intent intent):直接发动一个 Activity
  • startActivityForResult(Intent intent, int requestCode):带回来值的发动办法,这种发动办法现已被官方所抛弃,取而代之的是 registerForActivityResult(contract, mActivityResultRegistry, callback)

咱们从 startActivity 来一步步往下看:

public void startActivity(Intent intent) {
    this.startActivity(intent, null);
}
public void startActivity(Intent intent, @Nullable Bundle options) {
    if (options != null) {
        startActivityForResult(intent, -1, options);
    } else {
        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) {
        ......
        //execStartActivity
        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 {
        if (options != null) {
            //这儿终究也是调用 execStartActivity 办法
            mParent.startActivityFromChild(this, intent, requestCode, options);
        } else {
            mParent.startActivityFromChild(this, intent, requestCode);
        }
    }
}

上面代码中,调用了 execStartActivity 办法,该办法会回来一个发动成果。最下面的的 startActivityFromChild 办法终究也是调用的 execStartActivity。

咱们先看一下该办法的参数:

public ActivityResult execStartActivity(
        Context who, IBinder contextThread, IBinder token, Activity target,
        Intent intent, int requestCode, Bundle options) {
}
  1. Context who :传入的是 this,用来发动 Activity 的方针

  2. Ibinder contextThread:Binder 方针,具有跨进程通讯的能力,传入的是 mMainThread.getApplicationThread()

    public ApplicationThread getApplicationThread(){
        return mAppThread;
    }
    final ApplicationThread mAppThread = new ApplicationThread();
    private class ApplicationThread extends IApplicationThread.Stub {
    	.....
    }
    

    ApplicationThread 是 Activitythread 的内部类,便是经过 AIDL 创立的一个远程服务的接口,用来与服务端进行交互,该方针会被传入到 AMS 中,在 AMS 中回保存他的 client(客户端),这样 AMS 就能够与运用进程进行通讯了

  3. IBinder token:Binder 方针,指向了服务端一个 ActivityRecord 方针

  4. Activity target:当时的 Activity

  5. Intent intent, int requestCode, Bundle options :Intent 方针,恳求码和参数。

下面咱们来看一下 execStartActivity 办法:

public ActivityResult execStartActivity(
        Context who, IBinder contextThread, IBinder token, Activity target,
        Intent intent, int requestCode, Bundle options) {
    //运用端 AIDL 实现类
    IApplicationThread whoThread = (IApplicationThread) contextThread;
    .......
    try {
        intent.migrateExtraStreamToClipData(who);
        intent.prepareToLeaveProcess(who);
        //经过 Binder 调用 ATMS 发动 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);
        checkStartActivityResult(result, intent);
    } catch (RemoteException e) {
        throw new RuntimeException("Failure from system", e);
    }
    return null;
}
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);
            }
        };

咱们能够用一张图来表明上述的流程:

Android | Activity 启动流程分析

上面代码中经过 getService 获取到 Binder 方针,然后将 Binder 转成 AIDL 接口所属的类型,接着就能够调用 AIDL 中的办法与服务端进行通讯了。

接着调用 ATMS 中的 startActivity() 办法发起发动 Activity 恳求,获得发动成果 result。在调用 checkStartActivityResult 办法,传入 result,来判别能否发动 Activity,不能发动就会抛出反常,例如 activity 未在 manifest 中声明等。

二 、ATMS

经过上面的代码能够看出现已调用到了体系的 ATMS 当中,咱们来看一下详细的流程

#ActivityTaskManagerService.java
@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());
}
#ActivityTaskManagerService.java
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*/);
}
#ActivityTaskManagerService.java
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(bOptions)
            .setUserId(userId)
            .execute();
}

上面代码终究调用到了 startActivityAsUser 办法,在内部将所有点的参数都交给了 ActivityStarter ,该类包含了发动的所有逻辑,比如 Intent 解析以及使命栈等。

接着调用了obtainStarter ,该办法经过工厂形式创立了 ActivityStarter 方针,如下所示:

#ActivityStarter.java
static class DefaultFactory implements Factory {
    /**
     * ActivitySatrter 最大数量
     */
    private final int MAX_STARTER_COUNT = 3;
    ......
		//同步池
    private SynchronizedPool<ActivityStarter> mStarterPool =
            new SynchronizedPool<>(MAX_STARTER_COUNT);
    DefaultFactory(ActivityTaskManagerService service,
            ActivityTaskSupervisor supervisor, ActivityStartInterceptor interceptor) {
        mService = service;
        mSupervisor = supervisor;
        mInterceptor = interceptor;
    }
    @Override
    public void setController(ActivityStartController controller) {
        mController = controller;
    }
    @Override
    public ActivityStarter obtain() {
        //从同步池中获取 ActivityStarter 方针
        ActivityStarter starter = mStarterPool.acquire();
        if (starter == null) {
            if (mService.mRootWindowContainer == null) {
                throw new IllegalStateException("Too early to start activity.");
            }
            starter = new ActivityStarter(mController, mService, mSupervisor, mInterceptor);
        }
        return starter;
    }
    @Override
    public void recycle(ActivityStarter starter) {
        starter.reset(true /* clearRequest*/);
        mStarterPool.release(starter);
    }
}

能够看到,默许的工厂在供给了一个容量为 3 的同步缓存池来缓存 ActivityStarter 方针,该方针创立完结之后,该方针创立完结之后,AMTS 就会将接下来发动 Activity 的操作交给 ActivityStarter 来完结。

#ActivityStarter.java
//依据前面传入的参数解析一下必要的信息,并开端发动 Activity
int execute() {
    try {
        int res;
        synchronized (mService.mGlobalLock) {
            .....
            res = executeRequest(mRequest);//开端履行恳求
            .....
            return getExternalResult(res);
        }
    } finally {
        onExecutionComplete();
    }
}
#ActivityStarter.java
private int executeRequest(Request request) {
    .......
  	//检测Activity发动的权限
    boolean abort = !mSupervisor.checkStartAnyActivityPermission(intent, aInfo, 							resultWho,requestCode, callingPid, callingUid, callingPackage, 										callingFeatureId,request.ignoreTargetSecurity, inTask != null, 										callerApp, resultRecord, resultRootTask);
    abort |= !mService.mIntentFirewall.checkStartActivity(intent, callingUid,
            callingPid, resolvedType, aInfo.applicationInfo);
    abort |= !mService.getPermissionPolicyInternal().checkStartActivity(intent, callingUid,
            callingPackage);
    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();
    mLastStartActivityRecord = r;
    mLastStartActivityResult = startActivityUnchecked(r, sourceRecord, voiceSession,
            request.voiceInteractor, startFlags, true /* doResume */, checkedOptions, inTask,
            restrictedBgActivity, intentGrants);
    return mLastStartActivityResult;
}

上面代码中会进行一些校验和判别权限,包含进程查看,intent查看,权限查看等,后边就会创立 ActivityRecord ,每个 Activity 都会对应一个 ActivityRecord 方针,接着就会调用 startActivityUnchecked 办法对要发动的 Activity 做使命栈管理。

#ActivityStarter.java
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, Task inTask,
            boolean restrictedBgActivity, NeededUriGrants intentGrants) {
    int result = START_CANCELED;
    final Task startedActivityRootTask;
    try {
        mService.deferWindowLayout();
        Trace.traceBegin(Trace.TRACE_TAG_WINDOW_MANAGER, "startActivityInner");
        result = startActivityInner(r, sourceRecord, voiceSession, voiceInteractor,
                startFlags, doResume, options, inTask, restrictedBgActivity, intentGrants);
    } finally {
        Trace.traceEnd(Trace.TRACE_TAG_WINDOW_MANAGER);
        startedActivityRootTask = handleStartResult(r, result);
        mService.continueWindowLayout();
    }
    postStartActivityProcessing(r, result, startedActivityRootTask);
    return result;
}

在大多数开端查看现已完结的情况下开端进行下一步确认具有必要的权限。 上面的中心办法便是 startActivityInner() 用来查看发动所有必要要有的权限

#ActivityStarter.java
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);
		//判别发动形式,并且在 mLaunchFlags 上追加对应标记
    computeLaunchingTaskFlags();
		//设置 Activity 的栈
    computeSourceRootTask();
		//设置 LaunchFlags 到 intent 上
    mIntent.setFlags(mLaunchFlags);
  	//决定是否应将新活动插入现有使命中。回来null, 假如不是则应将新活动添加到其间的使命进行活动记录
    final Task reusedTask = getReusableTask();
    ......
    //reusedTask 为 null 则核算是否存在能够运用的使命栈
    final Task targetTask = reusedTask != null ? reusedTask : computeTargetTask();
    //是否需求创立栈  
    final boolean newTask = targetTask == null;
    mTargetTask = targetTask;
    computeLaunchParams(r, sourceRecord, targetTask);
    //查看是否答应在给定使命或新使命上发动活动
    int startResult = isAllowedToStart(r, newTask, targetTask);
    if (startResult != START_SUCCESS) {
        return startResult;
    }
    final ActivityRecord targetTaskTop = newTask
            ? null : targetTask.getTopNonFinishingActivity();
    if (targetTaskTop != null) {
        // Recycle the target task for this launch.
        startResult = recycleTask(targetTask, targetTaskTop, reusedTask, intentGrants);
        if (startResult != START_SUCCESS) {
            return startResult;
        }
    } else {
        mAddingToTask = true;
    }
  	//假如正在发动的活动与当时坐落顶部的活动相同
    //则需求查看它是否应该只发动一次
    final Task topRootTask = mPreferredTaskDisplayArea.getFocusedRootTask();
    if (topRootTask != null) {
        startResult = deliverToCurrentTopIfNeeded(topRootTask, intentGrants);
        if (startResult != START_SUCCESS) {
            return startResult;
        }
    }
    //复用或许创立新栈
    if (mTargetRootTask == null) {
        mTargetRootTask = getLaunchRootTask(mStartActivity, mLaunchFlags, targetTask, mOptions);
    }
    if (newTask) {
      	//新建一个 Task
        final Task taskToAffiliate = (mLaunchTaskBehind && mSourceRecord != null)
                ? mSourceRecord.getTask() : null;
        setNewTask(taskToAffiliate);
    } else if (mAddingToTask) {
        //复用之前的 Task
        addOrReparentStartingActivity(targetTask, "adding to task");
    }
 		......
    if (mDoResume) {
			// 调用 resumeFocusedTasksTopActivities办法
      mRootWindowContainer.resumeFocusedTasksTopActivities(
                    mTargetRootTask, mStartActivity, mOptions, mTransientLaunch);
    }
    mRootWindowContainer.updateUserRootTask(mStartActivity.mUserId, mTargetRootTask);
    .....
    return START_SUCCESS;
}

在上面办法中,依据发动形式核算出 flag,然后在依据 flag 等条件判别要发动的 Activity 的 ActivityRecord 是需求新创立 Task 栈 仍是加入到现有的 Task 栈。

在为 Activity 准备好 Task 栈之后,调用了 mRootWindowContainer.resumeFocuredTasksTopActivities 办法。

#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.java
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options,boolean deferPause) {
    if (mInResumeTopActivity) {
        // Don't even start recursing.
        return false;
    }
    boolean someActivityResumed = false;
    try {
        // Protect against recursion.
        mInResumeTopActivity = true;
        ....
        someActivityResumed = resumeTopActivityInnerLocked(prev,options,deferPause);
    } finally {
        mInResumeTopActivity = false;
    }
    return someActivityResumed;
}
#Task.java
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options,
        boolean deferPause) {
    if (!mAtmService.isBooting() && !mAtmService.isBooted()) {
        // Not ready yet!
        return false;
    }
    // 在当时 Task 栈中找到最上层正在运行的 Activity
    // 假如这个 Activity 没有获取焦点,那这个 Activity 将会被重新发动
    ActivityRecord next = topRunningActivity(true /* focusableOnly */);
    if (next.attachedToProcess()) {
        ......
    } else {
        ......
        //调用 ActivityTaskSupervisor.startSpecificActivity
        mTaskSupervisor.startSpecificActivity(next, true, true);
    }
    return true;
}
#ActivityTaskSupervisor.java
void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) {
        // 获取方针进程
        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) {
            }
            knownToBeDead = true;
        }
        r.notifyUnknownVisibilityLaunchedForKeyguardTransition();
        final boolean isTop = andResume && r.isTopRunningActivity();
        // 进程不存在,则创立进程,并发动 Activity
        mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity");
    }

假如进程不存在,则会创立进程,假如进程存在,则履行此办法

boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
        boolean andResume, boolean checkConfig) throws RemoteException {
    // 创立发动 Activity 的业务
    // proc.getThread() 获取的是一个 IApplicationThread 方针
    final ClientTransaction clientTransaction = ClientTransaction.obtain(
              proc.getThread(), r.appToken);
    final boolean isTransitionForward = r.isTransitionForward();
    // 为业务设置 Callback LaunchActivityItem,在客户端时会被调用
    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.getSavedState(), r.getPersistentSavedState(), results, newIntents,
            r.takeOptions(), isTransitionForward,
            proc.createProfilerInfoIfNeeded(), r.assistToken, 					
            activityClientController,
            r.createFixedRotationAdjustmentsIfNeeded(), r.shareableActivityToken,
            r.getLaunchedFromBubble()));
     // 生命周期方针
     final ActivityLifecycleItem lifecycleItem;
     if (andResume) {
         lifecycleItem = ResumeActivityItem.obtain(isTransitionForward);
     } else {
         lifecycleItem = PauseActivityItem.obtain();
     }
     // 设置生命周期恳求
     clientTransaction.setLifecycleStateRequest(lifecycleItem);
     // 履行业务
     mService.getLifecycleManager().scheduleTransaction(clientTransaction);
    return true;
}

上面代码的中心便是创立业务实例,然后来发动 Activity 。

ClientTransaction 是一个容器,里面包含了一些列的音讯,这些音讯会被发送到客户端,这些音讯包含了一系列的回谐和一个终究的生命周期状况。

ActivityLifecycleItem 用来恳求 Activity 应该抵达那个生命周期。

ClientLifecycleManager 用来履行业务

接着上面的代码往下走,就到了 scheduleTransaction()

void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
    // AIDL 接口,在客户端被实现,也便是 app 中
    final IApplicationThread client = transaction.getClient();
    //履行业务
    transaction.schedule();
    if (!(client instanceof Binder)) {
        transaction.recycle();
    }
}
public void schedule() throws RemoteException {
    mClient.scheduleTransaction(this);
}

mClient 便是 IApplicationThread 的实例,这儿是一个 IPC 调用,会直接调用到 App 进程中,并传入了 this,也便是 ClientTransaction 方针。

IApplicationThread 是 ApplicationThread 所实现的,他是 ActivityThread 的内部类

private class ApplicationThread extends IApplicationThread.Stub {
    @Override
    public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
        ActivityThread.this.scheduleTransaction(transaction);
    }
}

咱们用一张图来描绘一下上面的流程

Android | Activity 启动流程分析

在上面代码中查看 intent 以及各种权限,并且会获取发动形式,设置发动 Activity 的Task,最终判别 Activity 地点的进程是否存活,假如不存在则创立,假如存在则会经过 IPC 回调到 ApplicationThread 中去。

三、ActivityThread

经过上面,咱们知道了发动 Activity 终究有回调到 ApplicationThread,而它又是 ActivityThread 的子类。所以 上面代码终究调用到了 ActivityThread 的父类 ClientTransactionHandler 中:

void scheduleTransaction(ClientTransaction transaction) {
    transaction.preExecute(this);//处理
  	//发送音讯
    sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}
//创立的时分传入了 ActivityThread 实例
private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);
#ActivityThread$H
case EXECUTE_TRANSACTION:
    final ClientTransaction transaction = (ClientTransaction) msg.obj;
    mTransactionExecutor.execute(transaction);
    if (isSystem()) {
        transaction.recycle();
    }
    break;

上面代码中经过 TransactionExecutor 来履行业务:

public void execute(ClientTransaction transaction) {
    //履行回调
    executeCallbacks(transaction);
    //处理生命周期状况
    executeLifecycleState(transaction);
    mPendingActions.clear();
    if (DEBUG_RESOLVER) Slog.d(TAG, tId(transaction) + "End resolving transaction");
}
//处理生命周期状况
private void executeLifecycleState(ClientTransaction transaction) {
    final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
    if (lifecycleItem == null) {
        // No lifecycle request, return early.
        return;
    }
    final IBinder token = transaction.getActivityToken();
    final ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
    if (DEBUG_RESOLVER) {
        Slog.d(TAG, tId(transaction) + "Resolving lifecycle state: "
                + lifecycleItem + " for activity: "
                + getShortActivityName(token, mTransactionHandler));
    }
    if (r == null) {
        // Ignore requests for non-existent client records for now.
        return;
    }
    // 切换到对应的生命周期
    cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */, transaction);
    // Execute the final transition with proper parameters.
    lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
    lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
}
private void cycleToPath(ActivityClientRecord r, int finish, boolean excludeLastState,
        ClientTransaction transaction) {
    final int start = r.getLifecycleState();
    final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
    performLifecycleSequence(r, path, transaction);
}
//履行生命周期状况
private void performLifecycleSequence(ActivityClientRecord r, IntArray path,
        ClientTransaction transaction) {
    final int size = path.size();
    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 */, 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);
        }
    }
}

由所以新发动的 Activity,所以最开端履行的是 ON_CREATE 状况,也便是 handleLaunchActivity 办法, 而 mTransactionHandler 则是从结构办法中传入的,所以这儿调用你的便是 ActivityThread 中的办法。

#ActivityThread.java
public Activity handleLaunchActivity(ActivityClientRecord r,
        PendingTransactionActions pendingActions, Intent customIntent) {
	  //获取 Activity 的实例
    final Activity a = performLaunchActivity(r, customIntent);
    return a;
}
#ActivityThread.java
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    ActivityInfo aInfo = r.activityInfo;
    ContextImpl appContext = createBaseContextForActivity(r);
    Activity activity = null;
    try {
        //反射创立 Activity 
        java.lang.ClassLoader cl = appContext.getClassLoader();
        activity = mInstrumentation.newActivity(
                cl, component.getClassName(), r.intent);
        ......
    } catch (Exception e) {
        if (!mInstrumentation.onException(activity, e)) {
            throw new RuntimeException(
                "Unable to instantiate activity " + component
                + ": " + e.toString(), e);
        }
    }
    try {
        //假如没有 Application ,则进行创立
        Application app = r.packageInfo.makeApplication(false, mInstrumentation);
        ......
        if (activity != null) {
            Window window = null;
            if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
                window = r.mPendingRemoveWindow;
                r.mPendingRemoveWindow = null;
                r.mPendingRemoveWindowManager = null;
            }
 						....
            // 加载资源
            appContext.getResources().addLoaders(
                    app.getResources().getLoaders().toArray(new ResourcesLoader[0]));
            // 调用 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.configCallback,
                    r.assistToken, r.shareableActivityToken);
            //回调 onCreate 办法
            if (r.isPersistable()) {
                mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
            } else {
                mInstrumentation.callActivityOnCreate(activity, r.state);
            }
        }
        //设置当时状况
        r.setState(ON_CREATE);
				......
    } 
    return activity;
}

回调到 ActivityThread 后,会发送一个 EXECUTE_TRANSACTION 音讯,处理 system_server 传过来的 ClientTransaction。

详细的处理是在 TransactionExecutor 的 execute 办法中完结的,在里面会先履行各种回调,然后处理并切换到对应的生命周期。在依据对应的什么周期履行对应的办法。由于这儿是新建的 aCTIVITY ,所以状况是 ON_CREATE,就会履行 handleLaunchActivity 办法。

接着就会调用 performLaunchActivity 创立 Activity 的实例,调用 attach 初始化 activity,最终回调 activity 中的 onCreate 办法。

总结一下流程

  1. 调用 Activity 的 startActivity 办法来发动方针 Activity
  2. 接着就会调用到 Instrunmentation 的 execStartActivity 办法,经过获取 ATMS 的 binder 代理方针,然后调用到 ATMS 的 startActivity 中去
  3. 调用到 ATMS 中后,会履行到ActivityStarter 的 execute 办法,内部终究履行到了 executeRequest ,接着就会进行一些校验和判别权限,包含进程查看,intent查看,权限查看等,后边就会创立 ActivityRecord ,用来保存 Activity 的相关信息,
  4. 然后就会依据发动形式核算 flag ,设置发动 Activity 的 Task 栈。
  5. 在 ActivityTaskSupervisor 中查看要发动的 Activity 进程是否存在,存在则向客户端进程 ApplicationThread 回调发动 Activity,不然就创立进程。
  6. 会调到 ActivityThread 后在 TransactionExecute 中开端履行system_server回调回来的业务,处理各种回调,切换到对应的生命周期
  7. 最终又回调到 ActivityThread 的 handleLaunchActivity 来发动 Activity。在其间调用了 performLaunchActivity 办法。
  8. 在 performLaunchActivity 中经过反射创立 Activity 实例,假如没有 Application 则先进行创立,然后再调用Activity 的 attach 办法进行初始化,最终回调 activity 的 onCreate 办法。

参阅

Activity 发动流程

Android 深入研究之 ✨ Activity发动流程

ramework | Activity发动流程(android-31)

最终

文章到这儿就结束了,本文主要是剖析了一下运用内 Activity 的发动进程,由于我对整个发动的细节也不是十分了解,所以文章中或许有一些过错的当地,假如有还请指出,谢谢。假如对你有用请用你发财的小手点个赞!