❤️ Android 源码解读-startActivity(含启动新应用)❤️

开局一张图

源码版本:Android 11(SDK 30)

涉及到的类

  • Instrumentation:负责 Application 和 Activity 的建立和生命周期控制。

  • ActivityTaskManager:此类提供有关Activity及其容器(如任务、堆栈和显示)的信息并与之交互。

  • ActivityTaskManagerService:用于管理Activity及其容器(任务、显示等)的系统服务。之前这个活是AMS的,现在从AMS中剥离出来了。

  • ActivityStartController:用于委托Activity启动的控制器。

  • ActivityStarter:专门负责一个 Activity 的启动操做。它的主要做用包括解析 Intent、建立 ActivityRecord、若是有可能还要建立 TaskRecordflex

  • ActivityStack:Activity在ATMS的栈管理,用来记录已经启动的Activity的先后关系,状态信息等。通过ActivityStack决定是否需要启动新的进程。

  • RootWindowContainer:设备的Root WindowContainer。

  • TaskRecord:ATMS抽象出来的一个"任务"的概念,是记录ActivityRecord的栈,一个"Task"包含若干个ActivityRecord。ATMS用TaskRecord确保Activity启动和退出的顺序。

  • ActivityStackSupervisor:负责所有Activity栈的管理。内部管理了mHomeStack、mFocusedStack和mLastFocusedStack三个Activity栈。其中,mHomeStack管理的是Launcher相关的Activity栈;mFocusedStack管理的是当前显示在前台Activity的Activity栈;mLastFocusedStack管理的是上一次显示在前台Activity的Activity栈。

  • ActivitySupervisor:管理 activity 任务栈。

  • ActivityThread:ActivityThread 运行在UI线程(主线程),App的真正入口。

  • ApplicationThread:用来实现ATMS和ActivityThread之间的交互。

  • ApplicationThreadProxy:ApplicationThread 在服务端的代理。ATMS就是通过该代理与ActivityThread进行通信的。

  • ClientLifecycleManager:能够组合多个客户端生命周期 transaction 请求和/或回调,并将它们作为单个 transaction 执行。

  • TransactionExecutor:已正确的顺序管理 transaction 执行的类。

1、Activity.java

1.1 startActivity()

@Override
public void startActivity(Intent intent) {
//接着往里看
this.startActivity(intent, null);
}

@Override
public void startActivity(Intent intent, @Nullable Bundle options) {
...
if (options != null) {
startActivityForResult(intent, -1, options);
} else {
startActivityForResult(intent, -1);
}
}

最终调用了 startActivityForResult 方法,传入的 -1 表示不需要获取 startActivity 的结果。

1.2 startActivityForResult()

public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
@Nullable Bundle options) {
//mParent表示当前Activitiy的父类,
if (mParent == null) {
options = transferSpringboardActivityOptions(options);
//ActivityThread mMainThread;
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);
...
} else {
...
}
}

startActivityForResult 调用 Instrumentation.execStartActivity 方法。剩下的交给 Instrumentation 类去处理。

mMainThread 是 ActivityThread 类型,ActivityThread 可以理解为一个进程,这就是 Activity 所在的进程。

通过 mMainThread 获取一个 ApplicationThread 的引用,这个引用就是用来实现进程间通信的,具体来说就是 AMS 所在系统进程通知应用程序进程进行的一系列操作。

上面有Instrumentation、ActivityThread、ApplicationThread 等类的介绍。

2、Instrumentation.java

frameworks/base/core/java/android/app/Instrumentation.java

/**
* Base class for implementing application instrumentation code.
*/

public class Instrumentation {
...
}

2.1 execStartActivity()

 public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
...
try {
intent.migrateExtraStreamToClipData();
intent.prepareToLeaveProcess(who);
int result = ActivityTaskManager.getService()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target != null ? target.mEmbeddedID : null,
requestCode, 0, null, options);
//检查启动Activity的结果
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
}
return null;
}

在 Instrumentation 中,调用了 ActivityTaskManager.getService().startActivity() 。咱们近距离观望一下。

3、ActivityTaskManage.java

frameworks/base/core/java/android/app/ActivityTaskManager.java

@TestApi
@SystemService(Context.ACTIVITY_TASK_SERVICE)
public class ActivityTaskManager {
...
}

3.1 getService()

    /** @hide */
public static IActivityTaskManager getService() {
return IActivityTaskManagerSingleton.get();
}

3.2 IActivityTaskManagerSingleton

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

这里实际上返回的是一个 ActivityTaskManagerService 这出现了跨进程 (从应用进程(app) > system_service进程) ,然后调用其 startActivity 方法。

实际上这里就是通过 AIDL 来调用 ATMS 的 startActivity 方法,返回 IActivityTaskManager.startActivity 的结果:Activity 已正常成功启动。

至此,startActivity 的工作重心成功地从 应用进程(app) 转移到了系统进程(system_service) 的 ATMS 中。

4、ActivityTaskManagerService.java

frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java

/**
* 用于管理 activities and their containers (task, stacks, displays,... )的 system_service(系统服务)
*/

public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
...
}

4.1 startActivity()

@Override
public final int startActivity(IApplicationThread caller, String callingPackage,
String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
Bundle bOptions) {
return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions,
UserHandle.getCallingUserId());
}

4.2 startActivityAsUser()

@Override
public int startActivityAsUser(IApplicationThread caller, String callingPackage,
String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
Bundle bOptions, int userId) {
return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
true /*validateIncomingUser*/);
}

4.3 startActivityAsUser() 比上面多个参数

//重点来了
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");

// 在此处切换到用户app堆栈。
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();

}

4.4 getActivityStartController()

    ActivityStartController getActivityStartController() {
return mActivityStartController;
}

5、ActivityStartController.java

/**
* Controller for delegating activity launches.
*/

public class ActivityStartController {
...
}

5.1 obtainStarter();

    /**
* @return A starter to configure and execute starting an activity. It is valid until after
* {@link ActivityStarter#execute} is invoked. At that point, the starter should be
* considered invalid and no longer modified or used.
*/

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

6、ActivityStarter.java

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 {
...
}

6.1 execute()

    /**
* 根据前面提供的请求参数解析必要的信息,执行开始活动的请求。
* @return The starter result.
*/

int execute() {
...
res = executeRequest(mRequest);
...
}

6.2 executeRequest()

    /**
* Activity启动之前需要做那些准备?
* 通常的Activity启动流程将通过 startActivityUnchecked 到 startActivityInner。
*/

private int executeRequest(Request request) {
...
//Activity的记录
ActivityRecord sourceRecord = null;
ActivityRecord resultRecord = null;
...
//Activity stack(栈)管理
mLastStartActivityResult = startActivityUnchecked(r, sourceRecord, voiceSession,
request.voiceInteractor, startFlags, true /* doResume */, checkedOptions, inTask,
restrictedBgActivity, intentGrants);

...
return mLastStartActivityResult;
}

从上面代码可以看出,经过多个方法的调用,最终通过 obtainStarter 方法获取了 ActivityStarter 类型的对象,然后调用其 execute() 方法。

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

咱们接着看看 startActivityUnchecked() ;

6.3 startActivityUnchecked()

    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 {
...
}

postStartActivityProcessing(r, result, startedActivityRootTask);

return result;
}

6.4 startActivityInner()

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

//计算启动模式
computeLaunchingTaskFlags();
computeSourceRootTask();
//设置启动模式
mIntent.setFlags(mLaunchFlags);

...

// 关键点来了
mRootWindowContainer.resumeFocusedTasksTopActivities(
mTargetRootTask, mStartActivity, mOptions, mTransientLaunch);
...

return START_SUCCESS;
}

这个是 mRootWindowContainer 是 RootWindowContainer

7、RootWindowContainer.java

frameworks/base/services/core/java/com/android/server/wm/RootWindowContainer.java

/** Root {@link WindowContainer} for the device. */
class RootWindowContainer extends WindowContainer<DisplayContent>
implements DisplayManager.DisplayListener {
...
}

7.1 resumeFocusedTasksTopActivities()

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

当然这里看的是 targetRootTask 是 Task 对象的实例。咱们就去追踪这个方法。

8、

0 个评论

要回复文章请先登录注册