了解Activity启动过程,从startActivity到ATMS的高效协作

移动开发 Android
在Android的不同版本中,启动流程可能会有所不同,并且可能涉及到更多的细节和组件。此外,如果启动的是一个根Activity(例如从Launcher启动),那么流程中可能还包括应用进程的创建等步骤。

在Android系统中,启动一个Activity无论是从应用内部启动Activity,还是通过桌面程序(Launcher)启动,都需要通过调用startActivity方法来发起启动请求。

启动请求的发起

  1. 「应用内部启动Activity」:

当应用内部需要启动一个新的Activity时,开发者会调用startActivity方法,并传递一个包含目标Activity信息的Intent对象。

这个Intent对象可以指定要启动的Activity的类名、传递的数据、附加的extras等。

调用startActivity后,系统会开始处理启动请求,并按照Activity启动流程进行后续操作。

  1. 「Launcher启动Activity」:
  • Launcher是Android系统的桌面程序,它负责显示已安装的应用程序图标,并提供用户与应用程序交互的入口。

  • 当用户从Launcher点击一个应用程序图标时,Launcher会创建一个新的Intent,用于启动该应用程序的主Activity(通常是根Activity)。

  • 然后,Launcher调用startActivity方法,并将该Intent传递给系统,以启动目标Activity。

在两种情况下,启动请求的发起都是通过调用startActivity方法实现的。这个方法会触发一系列的操作,包括将启动请求传递给ActivityTaskManagerService(ATMS),进行线程切换和消息处理,以及最终完成Activity的初始化和显示。无论是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 {
            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);
                }
            };
}

当请求到达ATMS时,ATMS会首先检查该请求是否合法,包括检查Intent的有效性、权限等。一旦请求被验证为有效,ATMS会进一步处理这个请求。

处理过程中,ATMS会根据当前系统的状态和任务栈的情况来决定如何响应这个启动请求。例如,它可能会决定创建一个新的Activity实例,或者将已存在的Activity实例带到前台。ATMS还会与ActivityManagerService(AMS)进行交互,以协调应用程序组件的生命周期管理。AMS负责跟踪和管理这些组件的生命周期,确保它们按照预期的方式运行。

Activity的初始化与生命周期管理

当Activity启动请求到达ActivityTaskManagerService(ATMS)并被验证为有效后,ATMS会通知相应的应用进程进行Activity的初始化。

// /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");


        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
class ActivityStarter {

    int execute() {
        try {
            //...

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

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


    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();

        //权限检查
        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进行任务栈管理。

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; 
    mIntent = r.intent; 
    mSourceRecord = sourceRecord; 
    mLaunchMode = r.launchMode; 
    // 启动Flags
    mLaunchFlags = adjustLaunchFlagsToDocumentMode(
          r, LAUNCH_SINGLE_INSTANCE == mLaunchMode,
          LAUNCH_SINGLE_TASK == mLaunchMode, mIntent.getFlags());
    mInTask = inTask;
    // ...
}


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等条件判断要启动的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方法;进程不存在则创建进程。

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阶段设置的ClientTransaction的CallBack的execute方法,即LaunchActivityItem.execute方法,此时创建一个ActivityClientRecord对象,然后通过ActivityThread.handleLaunchActivity开启真正的Actvity启动。

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

}

当初始化完成后,Activity的界面会被绘制并显示到屏幕上。此时,用户可以与Activity进行交互。

总结

  1. 「启动请求的发起」:

无论是从应用内部启动Activity,还是通过桌面程序(Launcher)启动,都需要通过调用startActivity方法来发起启动请求。

这个请求包含了要启动的Activity的信息,通常通过Intent对象来传递。

  1. 「请求到达ActivityTaskManagerService(ATMS)」:
  • 当启动请求被发起后,它会首先到达ActivityTaskManagerService(ATMS)。

  • ATMS是负责管理Activity生命周期和任务栈的系统服务。

  1. 「线程切换与消息处理」:

  • 在ATMS处理启动请求的过程中,可能涉及到线程切换和消息处理。

  • 例如,将请求从应用线程切换到系统服务线程,或者通过消息队列来处理请求。

  1. 「Activity的初始化与生命周期管理」:

  • 一旦ATMS决定了要启动哪个Activity,它会通知相应的应用进程进行Activity的初始化。

  • 这包括创建Activity的实例、加载布局、初始化组件等。

  • 同时,Activity的生命周期方法(如onCreate、onStart、onResume等)也会被调用,以确保Activity的正确初始化和状态管理。

  1. 「Activity的显示」:

  • 当初始化完成后,Activity的界面会被绘制并显示到屏幕上。

  • 此时,用户可以与Activity进行交互。

在Android的不同版本中,启动流程可能会有所不同,并且可能涉及到更多的细节和组件。此外,如果启动的是一个根Activity(例如从Launcher启动),那么流程中可能还包括应用进程的创建等步骤。Activity的启动流程是一个涉及多个组件和服务的复杂过程,它确保了Android应用程序能够正确地创建、初始化和显示Activity,从而为用户提供流畅和一致的体验。

责任编辑:武晓燕 来源: 沐雨花飞蝶
相关推荐

2023-03-24 14:52:27

AbilityPage应用

2011-07-28 10:34:38

Cocoa 程序 启动

2014-06-23 10:31:09

Android启动过程

2011-09-05 17:35:18

MTK启动过程RTOS

2021-07-02 06:34:53

Go语言sysmon

2011-06-28 13:27:13

ARM Linux

2009-12-03 10:00:46

Linux系统启动

2010-07-05 17:38:39

IIS 7.0 FTP

2018-03-13 13:00:03

Linux运维启动分析

2012-02-20 14:47:08

JavaPlay

2012-08-16 09:07:57

Erlang

2023-12-09 08:58:30

AndroidActivity启动模式

2010-05-06 14:05:15

Unix系统

2024-09-11 09:25:03

Tomcat组件PREP

2021-09-28 15:03:06

Linux内核arm

2020-03-19 08:59:15

SpringMVC启动过程

2019-05-27 14:43:49

Tomcat架构部署

2018-10-18 14:06:15

Linux系统过程

2020-04-20 21:30:51

Tomcat部署架构

2009-08-11 09:03:45

Windows 7系统启动
点赞
收藏

51CTO技术栈公众号