Activity启动流程

以下源码基于android-11.0.0_r1

启动一个Activity,通常有两种情况:第一种是不同进程的的根activity,比如laucnher启动app;第二种是同进程内部启动activity。这两种情况的启动流程类似,大致分为以下三个步骤:

  1. 调用进程的activity收集好信息后,向system_server进程的ActivityTaskManagerSrvice服务发起请求。
  2. ATMS向PKMS寻找启动的activity的信息和进程信息,如果启动的activity没有被创建,则创建新进程,之后管理activity栈,并回调启动activity所在进程的ApplicationThread类。
  3. ApplicationThread通过调用ActivityThread来反射创建并启动Activity。

以下就逐一讲解这三大过程:

一、从startActivity到ATMS

下图是调用进程向system_server进程发起请求的过程:


无论是startActivity还是startActivityForResult最终都是调用startActivityForResult

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

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

    public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
            @Nullable Bundle options) {
        // mParent 是Activity类型,是当前Activity的父类
        if (mParent == null) {
            options = transferSpringboardActivityOptions(options);
            // 调用Instrumentation.execStartActivity启动activity
            Instrumentation.ActivityResult ar =
                mInstrumentation.execStartActivity(
                    this, mMainThread.getApplicationThread(), mToken, this,
                    intent, requestCode, options);
            ...
            
        } else {
            ...

        }
    }
}

startActivityForResult中继续调用Instrumentation.execStartActivity方法。Activity中的mInstrumentation是在attach()方法中初始化,由ActivityThread传入,其作用一是通过远程服务调用启动activity;二是连接ActivityThread与activity,处理activity生命周期回调。

// Instrumentation主要用来监控应用程序和系统的交互,比如调用ATMS启动activity,回调生命周期
public class Instrumentation {

    public ActivityResult execStartActivity(
        Context who, IBinder contextThread, IBinder token, Activity target,
        Intent intent, int requestCode, Bundle options) {
        ...

        try {
            ...
            
            // 通过ATMS远程调用startActivity
            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;
    }

    /**
     * 根据result判断当前能否启动activity,不能则抛出异常
     */
    public static void checkStartActivityResult(int res, Object intent) {
        if (!ActivityManager.isStartResultFatalError(res)) {
            return;
        }

        switch (res) {
            case ActivityManager.START_INTENT_NOT_RESOLVED:
            case ActivityManager.START_CLASS_NOT_FOUND:
                if (intent instanceof Intent && ((Intent)intent).getComponent() != null)
                    // 没有在manifest中声明
                    throw new ActivityNotFoundException(
                            "Unable to find explicit activity class "
                            + ((Intent)intent).getComponent().toShortString()
                            + "; have you declared this activity in your AndroidManifest.xml?");
                throw new ActivityNotFoundException(
                        "No Activity found to handle " + intent);
            case ActivityManager.START_PERMISSION_DENIED:
                throw new SecurityException("Not allowed to start activity "
                        + intent);
            case ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT:
                throw new AndroidRuntimeException(
                        "FORWARD_RESULT_FLAG used while also requesting a result");
            case ActivityManager.START_NOT_ACTIVITY:
                throw new IllegalArgumentException(
                        "PendingIntent is not an activity");
            case ActivityManager.START_NOT_VOICE_COMPATIBLE:
                throw new SecurityException(
                        "Starting under voice control not allowed for: " + intent);
            case ActivityManager.START_VOICE_NOT_ACTIVE_SESSION:
                throw new IllegalStateException(
                        "Session calling startVoiceActivity does not match active session");
            case ActivityManager.START_VOICE_HIDDEN_SESSION:
                throw new IllegalStateException(
                        "Cannot start voice activity on a hidden session");
            case ActivityManager.START_ASSISTANT_NOT_ACTIVE_SESSION:
                throw new IllegalStateException(
                        "Session calling startAssistantActivity does not match active session");
            case ActivityManager.START_ASSISTANT_HIDDEN_SESSION:
                throw new IllegalStateException(
                        "Cannot start assistant activity on a hidden session");
            case ActivityManager.START_CANCELED:
                throw new AndroidRuntimeException("Activity could not be started for "
                        + intent);
            default:
                throw new AndroidRuntimeException("Unknown error code "
                        + res + " when starting " + intent);
        }
    }
}
@SystemService(Context.ACTIVITY_TASK_SERVICE)
public class ActivityTaskManager {
    /**
     * IActivityTaskManager是一个Binder,用于和system_server进程中的ActivityTaskManagerService通信
     */
    public static IActivityTaskManager getService() {
        return IActivityTaskManagerSingleton.get();
    }

    private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton =
            new Singleton<IActivityTaskManager>() {
                @Override
                protected IActivityTaskManager create() {
                    final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);
                    return IActivityTaskManager.Stub.asInterface(b);
                }
            };
}
  1. ActivityTaskManager.getService()获取ATMS的代理类,通过Binder跨进程通信,向ATMS发起startActivity请求。
  2. 向ATMS发起启动activity请求,获得启动结果result,根据result判断能否启动activity,不能则抛出异常,比如activity未在manifest中声明。

二、ATMS到ApplicationThread

下图为ATMS到ApplicationThread时序图:


// /frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
public class ActivityTaskManagerService extends IActivityTaskManager.Stub {

    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);
        // 判断调用者进程是否被隔离
        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();
    }
}

ATMS通过一系列方法调用最终调到startActivityAsUser方法,该方法先检查调用者权限,再通过getActivityStartController().obtainStarter创建ActivityStarter类,把参数设置到ActivityStarter.Request类中,最后执行ActivityStarter. execute()方法。

// /frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java
/**
 * Controller for interpreting how and then launching an activity.
 *
 * This class collects all the logic for determining how an intent and flags should be turned into
 * an activity and associated task and stack.
 */
class ActivityStarter {

    /**
    * Resolve necessary information according the request parameters provided earlier, and execute
    * the request which begin the journey of starting an activity.
    * @return The starter result.
    */
    int execute() {
        try {
            ...


            int res;
            synchronized (mService.mGlobalLock) {
                ...
                
                res = executeRequest(mRequest);

                ...
            }
        } finally {
            onExecutionComplete();
        }
    }

    /**
    * Executing activity start request and starts the journey of starting an activity. Here
    * begins with performing several preliminary checks. The normally activity launch flow will
    * go through {@link #startActivityUnchecked} to {@link #startActivityInner}.
    */
    private int executeRequest(Request request) {
        // 判断启动的理由不为空
        if (TextUtils.isEmpty(request.reason)) {
            throw new IllegalArgumentException("Need to specify a reason.");
        }

        // 获取调用的进程
        WindowProcessController callerApp = null;
        if (caller != null) {
          callerApp = mService.getProcessController(caller);
          if (callerApp != null) {
              // 获取调用进程的pid和uid并赋值
              callingPid = callerApp.getPid();
              callingUid = callerApp.mInfo.uid;
          } else {
              err = ActivityManager.START_PERMISSION_DENIED;
          }
        }

        final int userId = aInfo != null && aInfo.applicationInfo != null
              ? UserHandle.getUserId(aInfo.applicationInfo.uid) : 0;

        ActivityRecord sourceRecord = null;
        ActivityRecord resultRecord = null;
        if (resultTo != null) {
          // 获取调用者所在的ActivityRecord
          sourceRecord = mRootWindowContainer.isInAnyStack(resultTo);
          if (sourceRecord != null) {
              if (requestCode >= 0 && !sourceRecord.finishing) {
                  //requestCode = -1 则不进入
                  resultRecord = sourceRecord;
              }
          }
        }

        final int launchFlags = intent.getFlags();
        if ((launchFlags & Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0 && sourceRecord != null) {
         ... // activity执行结果的返回由源Activity转换到新Activity, 不需要返回结果则不会进入该分支
        }

        if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) {
           // 从Intent中无法找到相应的Component
           err = ActivityManager.START_INTENT_NOT_RESOLVED;
        }

        if (err == ActivityManager.START_SUCCESS && aInfo == null) {
           // 从Intent中无法找到相应的ActivityInfo
           err = ActivityManager.START_CLASS_NOT_FOUND;
        }

        ...

        //执行后resultStack = null
        final ActivityStack resultStack = resultRecord == null
              ? null : resultRecord.getRootTask();

        ... //权限检查

        // ActivityController不为空的情况,比如monkey测试过程
        if (mService.mController != null) {
            try {
                Intent watchIntent = intent.cloneFilter();
                abort |= !mService.mController.activityStarting(watchIntent,
                      aInfo.applicationInfo.packageName);
            } catch (RemoteException e) {
              mService.mController = null;
            }
        }

        if (abort) {
            ... //权限检查不满足,才进入该分支则直接返回;
            return START_ABORTED;
        

        if (aInfo != null) {
            if (mService.getPackageManagerInternalLocked().isPermissionsReviewRequired(
                  aInfo.packageName, userId)) {
                ...
                // 向PKMS获取启动Activity的ResolveInfo
                rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId, 0,
                      computeResolveFilterUid(
                              callingUid, realCallingUid, request.filterCallingUid));
                // 向PKMS获取启动Activity的ActivityInfo
                aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags,
                      null /*profilerInfo*/);

            }
        }

        ...

        // 创建即将要启动的Activity的描述类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;

        ...

        // 调用 startActivityUnchecked
        mLastStartActivityResult = startActivityUnchecked(r, sourceRecord, voiceSession,
                request.voiceInteractor, startFlags, true /* doResume */, checkedOptions, inTask,
                restrictedBgActivity, intentGrants);

        if (request.outActivity != null) {
            request.outActivity[0] = mLastStartActivityRecord;
        }

        return mLastStartActivityResult;
    }
}

ActivityStarter中通过调用executeRequest方法,先做一系列检查,包括进程检查、intent检查、权限检查、向PKMS获取启动Activity的ActivityInfo等信息,然后调用startActivityUnchecked方法开始对要启动的activity做任务栈管理。

/**
 * Start an activity while most of preliminary checks has been done and caller has been
 * confirmed that holds necessary permissions to do so.
 * Here also ensures that the starting activity is removed if the start wasn't successful.
 */
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
            int startFlags, boolean doResume, ActivityOptions options, Task inTask,
            boolean restrictedBgActivity, NeededUriGrants intentGrants) {
    ...

    try {
        ...

        result = startActivityInner(r, sourceRecord, voiceSession, voiceInteractor,
                startFlags, doResume, options, inTask, restrictedBgActivity, intentGrants);
    } finally {
        
        ...
    }

    ...

    return result;
}

ActivityRecord mStartActivity;

private ActivityStack mSourceStack;
private ActivityStack mTargetStack;
private Task mTargetTask;


// 主要处理栈管理相关的逻辑
int startActivityInner(final ActivityRecord r, ActivityRecord sourceRecord,
                     IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
                     int startFlags, boolean doResume, ActivityOptions options, Task inTask,
                     boolean restrictedBgActivity, NeededUriGrants intentGrants) {
    // 初始化启动Activity的各种配置,在初始化前会重置各种配置再进行配置,
    // 这些配置包括:ActivityRecord、Intent、Task和LaunchFlags(启动的FLAG)等等
    setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession,
          voiceInteractor, restrictedBgActivity);

    // 给不同的启动模式计算出mLaunchFlags
    computeLaunchingTaskFlags();

    // 主要作用是设置ActivityStack
    computeSourceStack();

    // 将mLaunchFlags设置给Intent
    mIntent.setFlags(mLaunchFlags);

    // 确定是否应将新活动插入现有任务。如果不是,则返回null,
    // 或者返回带有应将新活动添加到其中的任务的ActivityRecord。
    final Task reusedTask = getReusableTask();

    //...

    // 如果reusedTask为null,则计算是否存在可以使用的任务栈
    final Task targetTask = reusedTask != null ? reusedTask : computeTargetTask();
    final boolean newTask = targetTask == null; // 启动Activity是否需要新创建栈
    mTargetTask = targetTask;

    computeLaunchParams(r, sourceRecord, targetTask);

    // 检查是否允许在给定任务或新任务上启动活动。
    int startResult = isAllowedToStart(r, newTask, targetTask);
    if (startResult != START_SUCCESS) {
        return startResult;
    }


    final ActivityStack topStack = mRootWindowContainer.getTopDisplayFocusedStack();
    if (topStack != null) {
        // 检查正在启动的活动是否与当前位于顶部的活动相同,并且应该只启动一次
        startResult = deliverToCurrentTopIfNeeded(topStack, intentGrants);
        if (startResult != START_SUCCESS) {
            return startResult;
        }
    }

    if (mTargetStack == null) {
        // 复用或者创建堆栈
        mTargetStack = getLaunchStack(mStartActivity, mLaunchFlags, targetTask, mOptions);
    }
    if (newTask) {
        // 新建一个task
        final Task taskToAffiliate = (mLaunchTaskBehind && mSourceRecord != null)
              ? mSourceRecord.getTask() : null;
        setNewTask(taskToAffiliate);
        if (mService.getLockTaskController().isLockTaskModeViolation(
              mStartActivity.getTask())) {
            Slog.e(TAG, "Attempted Lock Task Mode violation mStartActivity=" + mStartActivity);
            return START_RETURN_LOCK_TASK_MODE_VIOLATION;
        }
    } else if (mAddingToTask) {
        // 复用之前的task
        addOrReparentStartingActivity(targetTask, "adding to task");
    }

    ...

    // 检查是否需要触发过渡动画和开始窗口
    mTargetStack.startActivityLocked(mStartActivity,
          topStack != null ? topStack.getTopNonFinishingActivity() : null, newTask,
          mKeepCurTransition, mOptions);


    if (mDoResume) {

        //...
        // 调用RootWindowContainer的resumeFocusedStacksTopActivities方法
        mRootWindowContainer.resumeFocusedStacksTopActivities(
              mTargetStack, mStartActivity, mOptions);
    }

    // ...

    return START_SUCCESS;
}

// 初始化状态
private void setInitialState(ActivityRecord r, ActivityOptions options, Task inTask,
                           boolean doResume, int startFlags, ActivityRecord sourceRecord,
                           IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
                           boolean restrictedBgActivity) {

    reset(false /* clearRequest */); //重置状态
    mStartActivity = r; // 被启动的Activity
    mIntent = r.intent; //启动的intent
    mSourceRecord = sourceRecord; //发起启动的Activity
    mLaunchMode = r.launchMode; // 启动模式
    // 启动Flags
    mLaunchFlags = adjustLaunchFlagsToDocumentMode(
          r, LAUNCH_SINGLE_INSTANCE == mLaunchMode,
          LAUNCH_SINGLE_TASK == mLaunchMode, mIntent.getFlags());
    mInTask = inTask;
    // ...
}

// 根据不同启动模式计算出不同的mLaunchFlags
private void computeLaunchingTaskFlags() {
    if (mInTask == null) {
        if (mSourceRecord == null) {
            if ((mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) == 0 && mInTask == null) {
                mLaunchFlags |= FLAG_ACTIVITY_NEW_TASK;
            }
        } else if (mSourceRecord.launchMode == LAUNCH_SINGLE_INSTANCE) {
            mLaunchFlags |= FLAG_ACTIVITY_NEW_TASK;
        } else if (isLaunchModeOneOf(LAUNCH_SINGLE_INSTANCE, LAUNCH_SINGLE_TASK)) {
            mLaunchFlags |= FLAG_ACTIVITY_NEW_TASK;
        }
    }
}

// 设置ActivityStack
private void computeSourceStack() {
    if (mSourceRecord == null) {
        mSourceStack = null;
        return;
    }
    if (!mSourceRecord.finishing) {
        mSourceStack = mSourceRecord.getRootTask();
        return;
    }

    if ((mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) == 0) {
        mLaunchFlags |= FLAG_ACTIVITY_NEW_TASK;
        mNewTaskInfo = mSourceRecord.info;

        final Task sourceTask = mSourceRecord.getTask();
        mNewTaskIntent = sourceTask != null ? sourceTask.intent : null;
    }
    mSourceRecord = null;
    mSourceStack = null;
}

private Task getReusableTask() {
    // If a target task is specified, try to reuse that one
    if (mOptions != null && mOptions.getLaunchTaskId() != INVALID_TASK_ID) {
        Task launchTask = mRootWindowContainer.anyTaskForId(mOptions.getLaunchTaskId());
        if (launchTask != null) {
            return launchTask;
        }
        return null;
    }

    //标志位,如果为true,说明要放入已经存在的栈,
    // 可以看出,如果是设置了FLAG_ACTIVITY_NEW_TASK 而没有设置 FLAG_ACTIVITY_MULTIPLE_TASK,
    // 或者设置了singleTask以及singleInstance
    boolean putIntoExistingTask = ((mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0 &&
            (mLaunchFlags & FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
            || isLaunchModeOneOf(LAUNCH_SINGLE_INSTANCE, LAUNCH_SINGLE_TASK);
    // 重新检验
    putIntoExistingTask &= mInTask == null && mStartActivity.resultTo == null;
    ActivityRecord intentActivity = null;
    if (putIntoExistingTask) {
        if (LAUNCH_SINGLE_INSTANCE == mLaunchMode) {
            //如果是 singleInstance,那么就找看看之前存在的该实例,找不到就为null
            intentActivity = mRootWindowContainer.findActivity(mIntent, mStartActivity.info,
                    mStartActivity.isActivityTypeHome());
        } else if ((mLaunchFlags & FLAG_ACTIVITY_LAUNCH_ADJACENT) != 0) {
            // For the launch adjacent case we only want to put the activity in an existing
            // task if the activity already exists in the history.
            intentActivity = mRootWindowContainer.findActivity(mIntent, mStartActivity.info,
                    !(LAUNCH_SINGLE_TASK == mLaunchMode));
        } else {
            // Otherwise find the best task to put the activity in.
            intentActivity =
                    mRootWindowContainer.findTask(mStartActivity, mPreferredTaskDisplayArea);
        }
    }

    if (intentActivity != null
            && (mStartActivity.isActivityTypeHome() || intentActivity.isActivityTypeHome())
            && intentActivity.getDisplayArea() != mPreferredTaskDisplayArea) {
        // Do not reuse home activity on other display areas.
        intentActivity = null;
    }

    return intentActivity != null ? intentActivity.getTask() : null;
}

// 计算启动的Activity的栈
private Task computeTargetTask() {
    if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask
            && (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {
        // 返回null,应该新创建一个Task,而不是使用现有的Task
        return null;
    } else if (mSourceRecord != null) {
        // 使用源Activity的task
        return mSourceRecord.getTask();
    } else if (mInTask != null) {
        // 使用启动时传递的task
        return mInTask;
    } else {
        // 理论上的可能,不可能走到这里
        final ActivityStack stack = getLaunchStack(mStartActivity, mLaunchFlags,
                null /* task */, mOptions);
        final ActivityRecord top = stack.getTopNonFinishingActivity();
        if (top != null) {
            return top.getTask();
        } else {
            // Remove the stack if no activity in the stack.
            stack.removeIfPossible();
        }
    }
    return null;
}

startActivityInner方法中,根据启动模式计算出flag,再根据flag等条件判断要启动的activity的ActivityRecord是加入现有的Task栈中,还是创建新的Task栈。在未Activity准备好Task栈后,调用RootWindowContainer.resumeFocusedStacksTopActivities方法。

class RootWindowContainer extends WindowContainer<DisplayContent>
      implements DisplayManager.DisplayListener {

    boolean resumeFocusedStacksTopActivities(
            ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {

        //...
        boolean result = false;
        if (targetStack != null && (targetStack.isTopStackInDisplayArea()
                || getTopDisplayFocusedStack() == targetStack)) {
            // 调用ActivityStack.resumeTopActivityUncheckedLocked
            result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
        }
        //...
        return result;
    }
}

class ActivityStack extends Task {

    boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
      if (mInResumeTopActivity) {
          // Don't even start recurscheduleTransactionsing.
          return false;
      }

      boolean result = false;
      try {
          mInResumeTopActivity = true;
          // 继续调用resumeTopActivityInnerLocked
          result = resumeTopActivityInnerLocked(prev, options);

          final ActivityRecord next = topRunningActivity(true /* focusableOnly */);
          if (next == null || !next.canTurnScreenOn()) {
              checkReadyForSleep();
          }
      } finally {
          mInResumeTopActivity = false;
      }

      return result;
  }

  private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {

      // Find the next top-most activity to resume in this stack that is not finishing and is
      // focusable. If it is not focusable, we will fall into the case below to resume the
      // top activity in the next focusable task.
      // 在当前Task栈中找到最上层正在运行的activity,如果这个activity没有获取焦点,那这个activity将会被重新启动
      ActivityRecord next = topRunningActivity(true /* focusableOnly */);
      final boolean hasRunningActivity = next != null;

      if (next.attachedToProcess()) {
          ...
      } else {
          ...
          // 调用StackSupervisor.startSpecificActivity
          mStackSupervisor.startSpecificActivity(next, true, true);
      }
      return true;
  }
}

ActivityStack的作用的用于单个活动栈的管理。最终调到ActivityStackSupervisor . startSpecificActivity

public class ActivityStackSupervisor implements RecentTasks.Callbacks {

    // 检查启动Activity所在进程是否有启动,没有则先启动进程
    void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) {
        // 根据processName和Uid查找启动Activity的所在进程
        final WindowProcessController wpc =
                mService.getProcessController(r.processName, r.info.applicationInfo.uid);

        boolean knownToBeDead = false;

        if (wpc != null && wpc.hasThread()) {
            // 进程已经存在,则直接启动Activity
            try {
                // 启动Activity ,并返回
                realStartActivityLocked(r, wpc, andResume, checkConfig);
                return;
            } catch (RemoteException e) {
               ...
            }
            knownToBeDead = true;
        }

        // 所在进程没创建则调用ATMS.startProcessAsync创建进程并启动Activity
        mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity");
    }

    // 启动Activity的进程存在,则执行此方法 
    boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
                                    boolean andResume, boolean checkConfig) throws RemoteException {

        ...

        // 创建活动启动事务
        // proc.getThread()是一个IApplicationThread对象,可以通过ClientTransaction.getClient()获取
        final ClientTransaction clientTransaction = ClientTransaction.obtain(
                proc.getThread(), r.appToken);

        // 为事务设置Callback,为LaunchActivityItem,在客户端时会被调用
        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()));

        // 设置所需的最终状态
        final ActivityLifecycleItem lifecycleItem;
        if (andResume) {
            lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
        } else {
            lifecycleItem = PauseActivityItem.obtain();
        }
        clientTransaction.setLifecycleStateRequest(lifecycleItem);

        // 执行事件,调用ClientLifecycleManager.scheduleTransaction
        mService.getLifecycleManager().scheduleTransaction(clientTransaction);

        ...
        return true;
    }
}

ActivityStackSupervisor中,先检查要启动activity的进程是否存在,如果存在则调用realStartActivityLocked方法,通过ClientTransaction事务回调ApplicationThread. scheduleTransaction方法;如果进程不存在,则创建进程。

ATMS小结

  1. ActivityStarter中检查调用进程,intent,权限等检查,通过PKMS获取ResolveInfo,ActivityInfo信息,符合条件的则往下走。
  2. ActivityStarter中根据启动模式计算flag,设置启动activity的Task栈。
  3. ActivityStackSupervisor检查要启动的activity的进程是否存在,存在则向客户端进程ApplicationThread回调启动Activity;否则创建进程。

三、ApplicationThread到启动Activity

下图为ActivityThread启动Activity过程的时序图:


// 主要是处理AMS端的请求
private class ApplicationThread extends IApplicationThread.Stub {
    @Override
    public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
        ActivityThread.this.scheduleTransaction(transaction);
    }
}

// ActivityThread的父类
public abstract class ClientTransactionHandler {

    void scheduleTransaction(ClientTransaction transaction) {
        transaction.preExecute(this);
        // 发送EXECUTE_TRANSACTION消息
        sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
    }
}

// 它管理应用程序进程中主线程的执行,根据活动管理器的请求,在其上调度和执行活动、广播和其他操作。
public final class ActivityThread extends ClientTransactionHandler {

    class H extends Handler {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case EXECUTE_TRANSACTION:
                    final ClientTransaction transaction = (ClientTransaction) msg.obj;
                    // 调用TransactionExecutor.execute去处理ATMS阶段传过来的ClientTransaction
                    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();
                    }
                    break;
            }
        }
    }
}

public class TransactionExecutor {
    public void execute(ClientTransaction transaction) {
        //...
        // 调用传过来的ClientTransaction事务的Callback
        executeCallbacks(transaction);

        executeLifecycleState(transaction);
    }

    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);
            ...
            // 调用LaunchActivityItem.execute
            item.execute(mTransactionHandler, token, mPendingActions);
            item.postExecute(mTransactionHandler, token, mPendingActions);
            ...
        }
    }
}

public class LaunchActivityItem extends ClientTransactionItem {
    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, mIsForward,
                mProfilerInfo, client, mAssistToken, mFixedRotationAdjustments);
        // 调用ActivityThread.handleLaunchActivity
        client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
    }
}

ApplicationThread类绕了一大圈,最后调用在ATMS阶段设置的ClientTransactionCallBackexecute方法,也就是LaunchActivityItem.execute方法,此方法创建一个ActivityClientRecord对象,然后调用ActivityThread. handleLaunchActivity开启真正的Actvity启动。

真正启动activity:
public final class ActivityThread extends ClientTransactionHandler {
    // ActivityThread启动Activity的过程
    @Override
    public Activity handleLaunchActivity(ActivityClientRecord r,
                                         PendingTransactionActions pendingActions, Intent customIntent) {
        // ...
        WindowManagerGlobal.initialize();
        // 启动Activity
        final Activity a = performLaunchActivity(r, customIntent);
    
        if (a != null) {
           ...
        } else {
            // 启动失败,调用ATMS停止Activity启动
            try {
                ActivityTaskManager.getService()
                        .finishActivity(r.token, Activity.RESULT_CANCELED, null,
                                Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
            } catch (RemoteException ex) {
                throw ex.rethrowFromSystemServer();
            }
        }
    
    return a;
}

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    // 获取ActivityInfo类
    ActivityInfo aInfo = r.activityInfo;
    if (r.packageInfo == null) {
        // 获取APK文件的描述类LoadedApk
        r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
                Context.CONTEXT_INCLUDE_CODE);
    }
    // 启动的Activity的ComponentName类
    ComponentName component = r.intent.getComponent();

    // 创建要启动Activity的上下文环境
    ContextImpl appContext = createBaseContextForActivity(r);
    Activity activity = null;
    try {
        java.lang.ClassLoader cl = appContext.getClassLoader();
        // 用类加载器来创建该Activity的实例
        activity = mInstrumentation.newActivity(
                cl, component.getClassName(), r.intent);
        // ...
    } catch (Exception e) {
        // ...
    }

    try {
        // 创建Application
        Application app = r.packageInfo.makeApplication(false, mInstrumentation);

        if (activity != null) {
            // 初始化Activity
            activity.attach(appContext, this, getInstrumentation(), r.token,
                    r.ident, app, r.intent, r.activityInfo, title, r.parent,
                    r.embeddedID, r.lastNonConfigurationInstances, config,
                    r.referrer, r.voiceInteractor, window, r.configCallback,
                    r.assistToken);

            ...
            // 调用Instrumentation的callActivityOnCreate方法来启动Activity
            if (r.isPersistable()) {
                mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
            } else {
                mInstrumentation.callActivityOnCreate(activity, r.state);
            }
          ...
        }
      ...

    } catch (SuperNotCalledException e) {
        throw e;

    } catch (Exception e) {
        ...
    }

    return activity;
}


public class Instrumentation {

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

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

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

    @UnsupportedAppUsage
    final void performCreate(Bundle icicle, PersistableBundle persistentState) {
        ...
        // 调用onCreate方法
        if (persistentState != null) {
            onCreate(icicle, persistentState);
        } else {
            onCreate(icicle);
        }
        ...
    }

}
小结:
  1. ActivityThread.mH中处理EXECUTE_TRANSACTION消息,处理从system_server进程传过来的ClientTransaction,然后回调ClientTransactionItemexecute()方法,而这个ClientTransactionItem就是在ActivityStakSupervisor类的realStartActivityLocked()方法中设置的其子类LaunchActivityItem
  2. 调用LaunchActivityItemexecute()方法,创建了一个ActivityClientRecord,对应system_server进程中的ActivityRecord,其作用是封装保存一个activity的相关信息,并传递到ActivityThread中。
  3. 继续回到ActivityThread中,通过一系列调用,最终来到performLaunchActivity方法:
  • 为ActivityInfo设置packageInfo,是一个LoadedApk类,用来保存当前应用的一些信息,如包名,资源目录等;
  • 创建要启动activity的上下文环境;
  • 通过Instrumentation实例化activity;
  • 创建Application;
  • 调用activity.attach()方法,初始化activity;
  • 调用Instrumentation.callActivityOnCreate()方法启动activity,并在activity的performCreate()方法中回调生命周期onCreate();

最后附一张完整流程图:


Activity启动流程图
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,222评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,455评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,720评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,568评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,696评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,879评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,028评论 3 409
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,773评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,220评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,550评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,697评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,360评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,002评论 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,782评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,010评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,433评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,587评论 2 350

推荐阅读更多精彩内容