在 Android 中,桌面应用 Launcher 由 Launcher 演变到 Launcher2,再到现在的 Launcher3,Google 也做了很多改动。 Launcher 不支持桌面小工具动画效果,Launcher2 添加了动画效果和 3D 效果支持,从 Android 4.4 开始 Launcher 默认使用 Launcher3,Launcher3 加入了透明状态栏,增加 overview 模式,可以调整 workspace 上页面的前后顺序,可以动态管理屏幕数量,widget 列表和 app list 分开显示等功能.我们主要研究 Launcher3 的启动过程。
涉及到的源码如下:
/frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
/frameworks/base/core/java/com/android/internal/os/ZygoteServer.java
/frameworks/base/core/java/com/android/internal/os/ZygoteConnection.java
/frameworks/base/core/java/com/android/internal/os/Zygote.java
/frameworks/base/core/java/com/android/internal/os/RuntimeInit.java
/frameworks/base/services/java/com/android/server/SystemServer.java
/frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
/frameworks/base/services/core/java/com/android/server/am/ProcessList.java
/frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
/frameworks/base/services/core/java/com/android/server/wm/ActivityStartController.java
/frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java
/frameworks/base/services/core/java/com/android/server/wm/ActivityStack.java
/frameworks/base/services/core/java/com/android/server/wm/ActivityStackSupervisor.java
/frameworks/base/services/core/java/com/android/server/wm/RootActivityContainer.java
/frameworks/base/services/core/java/com/android/server/wm/ClientLifecycleManager.java
/frameworks/base/core/java/android/os/Process.java
/frameworks/base/core/java/android/os/ZygoteProcess.java
/frameworks/base/core/java/android/app/ActivityThread.java
/frameworks/base/core/java/android/app/Activity.java
/frameworks/base/core/java/android/app/ActivityManagerInternal.java
/frameworks/base/core/java/android/app/servertransaction/ClientTransaction.java
/frameworks/base/core/java/android/app/servertransaction/ClientTransaction.aidl
/frameworks/base/core/java/android/app/ClientTransactionHandler.java
/frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java
/frameworks/base/core/java/android/app/servertransaction/LaunchActivityItem.java
/frameworks/base/core/java/android/app/Instrumentation.java
/frameworks/base/services/core/java/com/android/server/pm/PackageManagerService.java
从上面的代码路徑可以看出,Android10 中 Activity 的相关功能被放到了 wm 的目录中,在 Android9.0 中是在 am 目录中,Google 最终的目的是把 activity 和 window 融合,在 Android10 中只是做了简单的代码路径的变更,真正的功能还要到后面的版本才能慢慢融合。
主要代码介绍:
Launcher 启动时序图
在 AMS 启动过程中,我们知道了 AMS 启动完成前,在 systemReady() 中会去调用 startHomeOnAllDisplays() 来启动 Launcher,本次就从 startHomeOnAllDisplays() 函数入口,来看看 Launcher 是如何被启动起来的。
[ActivityManagerService.java]
public void systemReady(final Runnable goingCallback, TimingsTraceLog
traceLog) {
........
//启动Home Activity
mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");
........
}
Launcher 的启动主要分为三部分:
接下来我们从源码上来分别分析这三个启动过程。
调用栈如下:
ActivityTaskManagerInternal 是 ActivityTaskManagerService 的一个抽象类,真正的实现是在 ActivityTaskManagerService 的 LocalService,所以 mAtmInternal.startHomeOnAllDisplays() 最终调用的是 ActivityTaskManagerService 的 startHomeOnAllDisplays() 方法
public boolean startHomeOnAllDisplays(int userId, String reason) {
synchronized (mGlobalLock) {
//调用到RootActivityContainer的startHomeOnDisplay()
return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
}
}
boolean startHomeOnAllDisplays(int userId, String reason) {
boolean homeStarted = false;
for (int i = mActivityDisplays.size() - 1; i >= 0; i--) {
final int displayId = mActivityDisplays.get(i).mDisplayId;
homeStarted |= startHomeOnDisplay(userId, reason, displayId);
}
return homeStarted;
}
boolean startHomeOnDisplay(int userId, String reason, int displayId, boolean allowInstrumenting,
boolean fromHomeKey) {
........
if (displayId == DEFAULT_DISPLAY) {
//构建一个category为CATEGORY_HOME的Intent,表明是Home Activity
homeIntent = mService.getHomeIntent();
//通过PKMS从系统所有已安装的应用中,找到一个符合HomeItent的Activity
aInfo = resolveHomeActivity(userId, homeIntent);
}
........
//启动Home Activity
mService.getActivityStartController().startHomeActivity(homeIntent, aInfo, myReason,
displayId);
return true;
}
获取的 displayId 为 DEFAULT_DISPLAY, 首先通过 getHomeIntent 来构建一个 category 为 CATEGORY_HOME 的 Intent,表明是 Home Activity,然后通过 resolveHomeActivity() 从系统所有已安装的应用中,找到一个符合 HomeItent 的 Activity,最终调用 startHomeActivity()来启动 Activity.
Intent getHomeIntent() {
Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
intent.setComponent(mTopComponent);
intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
//不是生产模式,add一个CATEGORY_HOME
if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
intent.addCategory(Intent.CATEGORY_HOME);
}
return intent;
}
构建一个 category 为 CATEGORY_HOME 的 Intent,表明是 Home Activity。Intent.CATEGORY_HOME = “android.intent.category.HOME”,这个 category 会在 Launcher3 的 AndroidManifest.xml 中配置,表明是 Home Acivity.
ActivityInfo resolveHomeActivity(int userId, Intent homeIntent) {
final int flags = ActivityManagerService.STOCK_PM_FLAGS;
final ComponentName comp = homeIntent.getComponent(); //系统正常启动时,component为null
ActivityInfo aInfo = null;
........
if (comp != null) {
// Factory test.
aInfo = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId);
} else {
//系统正常启动时,走该流程
final String resolvedType =
homeIntent.resolveTypeIfNeeded(mService.mContext.getContentResolver());
//resolveIntent做了两件事:
//1.通过queryIntentActivities来查找符合HomeIntent需求Activities
//2.通过chooseBestActivity找到最符合Intent需求的Activity信息
final ResolveInfo info = AppGlobals.getPackageManager()
.resolveIntent(homeIntent, resolvedType, flags, userId);
if (info != null) {
aInfo = info.activityInfo;
}
}
........
aInfo = new ActivityInfo(aInfo);
aInfo.applicationInfo = mService.getAppInfoForUser(aInfo.applicationInfo, userId);
return aInfo;
}
通过 Binder 跨进程通知 PackageManagerService 从系统所用已安装的应用中,找到一个符合 HomeItent 的 Activity.
void startHomeActivity(Intent intent, ActivityInfo aInfo, String reason, int displayId) {
........
//返回一个 ActivityStarter 对象,它负责 Activity 的启动
//一系列setXXX()方法传入启动所需的各种参数,最后的execute()是真正的启动逻辑
//最后执行ActivityStarter的execute方法
mLastHomeActivityStartResult = obtainStarter(intent, "startHomeActivity: " + reason)
.setOutActivity(tmpOutRecord)
.setCallingUid(0)
.setActivityInfo(aInfo)
.setActivityOptions(options.toBundle())
.execute();
mLastHomeActivityStartRecord = tmpOutRecord[0];
final ActivityDisplay display =
mService.mRootActivityContainer.getActivityDisplay(displayId);
final ActivityStack homeStack = display != null ? display.getHomeStack() : null;
if (homeStack != null && homeStack.mInResumeTopActivity) {
//如果home activity处于顶层的resume activity中,则Home Activity将被初始化,
//但不会被恢复(避免递归恢复),并将保持这种状态,直到有东西再次触发它。我们需要进行另一次恢复。
mSupervisor.scheduleResumeTopActivities();
}
}
接着看 startHomeActivity 函数,其中的 obtainStarter() 方法返回的是 ActivityStarter 对象,它负责 Activity 的启动,一系列 setXXX() 方法传入启动所需的各种参数,最后的 execute() 是真正的启动逻辑。另外如果 home activity 处于顶层的 resume activity 中,则 Home Activity 将被初始化,但不会被恢复,并将保持这种状态,直到有东西再次触发它。我们需要进行另一次恢复。
int execute() {
........
if (mRequest.mayWait) {
return startActivityMayWait(...)
} else {
return startActivity(...)
}
........
}
obtainStarter 没有调用 setMayWait 的方法,因此 mRequest.mayWait 为 false,走 startActivity 流程.
private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity, boolean restrictedBgActivity) {
........
try {
mService.mWindowManager.deferSurfaceLayout();//延时布局
//调用startActivityUnchecked ,一路调用到resumeFocusedStacksTopActivities()
result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
startFlags, doResume, options, inTask, outActivity, restrictedBgActivity);
} finally {
mService.mWindowManager.continueSurfaceLayout();//恢复布局
}
........
}
延时布局,然后通过 startActivityUnchecked() 来处理启动标记 flag ,要启动的任务栈等,最后恢复布局
boolean resumeFocusedStacksTopActivities(
ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
........
//如果目标栈就是栈顶Activity,启动resumeTopActivityUncheckedLocked()
if (targetStack != null && (targetStack.isTopStackOnDisplay()
|| getTopDisplayFocusedStack() == targetStack)) {
result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
........
if (!resumedOnDisplay) {
// 获取栈顶的 ActivityRecord
final ActivityStack focusedStack = display.getFocusedStack();
if (focusedStack != null) {
//最终调用startSpecificActivityLocked()
focusedStack.resumeTopActivityUncheckedLocked(target, targetOptions);
}
}
}
}
获取栈顶的 Activity,恢复它.
void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
........
//发送消息以启动进程,以避免在ATM锁保持的情况下调用AMS时可能出现死锁
//最终调用到AMS的startProcess()
final Message msg = PooledLambda.obtainMessage(
ActivityManagerInternal::startProcess, mService.mAmInternal, r.processName,
r.info.applicationInfo, knownToBeDead, "activity", r.intent.getComponent());
mService.mH.sendMessage(msg);
........
}
发送消息以启动进程,以避免在 ATM 锁保持的情况下调用 AMS 时可能出现死锁,最终调用到 ATM 的 startProcess().
public void startProcess(String processName, ApplicationInfo info,
boolean knownToBeDead, String hostingType, ComponentName hostingName) {
........
//同步操作,避免死锁
synchronized (ActivityManagerService.this) {
//调用startProcessLocked,然后到Process的start
//用来fork一个新的Launcher的进程
startProcessLocked(processName, info, knownToBeDead, 0 /* intentFlags */,
new HostingRecord(hostingType, hostingName),
false /* allowWhileBooting */, false /* isolated */,
true /* keepIfLarge */);
}
........
}
一路调用到 Process start(),最终到 ZygoteProcess 的 attemptUsapSendArgsAndGetResult(),用来 fork 一个新的 Launcher 进程
private Process.ProcessStartResult attemptZygoteSendArgsAndGetResult(
ZygoteState zygoteState, String msgStr) throws ZygoteStartFailedEx {
try {
//传入的zygoteState为openZygoteSocketIfNeeded()
//里面会通过abi来检查是第一个zygote还是第二个
final BufferedWriter zygoteWriter = zygoteState.mZygoteOutputWriter;
final DataInputStream zygoteInputStream = zygoteState.mZygoteInputStream;
//把应用进程的一些参数写给前面连接的zygote进程
//包括前面的processClass ="android.app.ActivityThread"
zygoteWriter.write(msgStr);
zygoteWriter.flush(); //进入Zygote进程,处于阻塞状态
//从socket中得到zygote创建的应用pid,赋值给 ProcessStartResult的对象
Process.ProcessStartResult result = new Process.ProcessStartResult();
result.pid = zygoteInputStream.readInt();
result.usingWrapper = zygoteInputStream.readBoolean();
if (result.pid < 0) {
throw new ZygoteStartFailedEx("fork() failed");
}
return result;
} catch (IOException ex) {
zygoteState.close();
Log.e(LOG_TAG, "IO Exception while communicating with Zygote - "
+ ex.toString());
throw new ZygoteStartFailedEx(ex);
}
}
通过 Socket 连接 zygote 进程,把之前组装的 msg 发给 zygote,其中 processClass = “android.app.ActivityThread”,通过 zygote 进程 fork 出一个新的进程,并执行 “android.app.ActivityThread” 的 main 方法.
zygote 的启动过程我们前面已经详细介绍过。SystemServer 的 AMS 服务通过 Socket 向 zygote 进程发送启动 Launcher 进程的请求,zygote 进程通过 Linux 的 fork 函数,孵化出一个新的进程。由于 zygote 进程在启动时会创建 Java 虚拟机,因此通过 fork 而创建的 Launcher 进程可以在内部获取一个 Java 虚拟机的实例。fork 采用 copy-on-write 机制,有些类如果不做改变,甚至都不用复制,子进程可以和父进程共享这部分数据,从而省去不少内存的占用。fork 过程,参考下图:
public static void main(String argv[]) {
........
Runnable caller;
........
if (startSystemServer) {
//Zygote Fork出的第一个进程 SystmeServer
Runnable r = forkSystemServer(abiList, zygoteSocketName, zygoteServer);
if (r != null) {
r.run();
return;
}
}
........
//循环等待fork出其他的应用进程,比如Launcher
//最终通过调用processOneCommand()来进行进程的处理
caller = zygoteServer.runSelectLoop(abiList);
........
if (caller != null) {
caller.run(); //执行返回的Runnable对象,进入子进程
}
}
zygote 先 fork 出 SystemServer 进程,接着进入循环等待,用来接收 Socket 发来的消息,用来 fork 出其他应用进程,比如 Launcher.
Runnable processOneCommand(ZygoteServer zygoteServer) {
int pid = -1;
........
//fork子进程,得到一个新的pid
/fork子进程,采用copy on write方式,这里执行一次,会返回两次
///pid=0 表示Zygote fork子进程成功
//pid > 0 表示子进程 的真正的PID
pid = Zygote.forkAndSpecialize(parsedArgs.mUid, parsedArgs.mGid, parsedArgs.mGids,
parsedArgs.mRuntimeFlags, rlimits, parsedArgs.mMountExternal, parsedArgs.mSeInfo,
parsedArgs.mNiceName, fdsToClose, fdsToIgnore, parsedArgs.mStartChildZygote,
parsedArgs.mInstructionSet, parsedArgs.mAppDataDir, parsedArgs.mTargetSdkVersion);
........
if (pid == 0) {
// in child, fork成功,第一次返回的pid = 0
.........
return handleChildProc(parsedArgs, descriptors, childPipeFd,
parsedArgs.mStartChildZygote);
} else {
.
........
childPipeFd = null;
handleParentProc(pid, descriptors, serverPipeFd);
return null;
}
}
通过 forkAndSpecialize() 来 fork 出 Launcher 的子进程,并执行 handleChildProc,进入子进程的处理.
private Runnable handleChildProc(ZygoteArguments parsedArgs, FileDescriptor[] descriptors,
FileDescriptor pipeFd, boolean isZygote) {
........
if (parsedArgs.mInvokeWith != null) {
........
throw new IllegalStateException("WrapperInit.execApplication unexpectedly returned");
} else {
if (!isZygote) {
// App进程将会调用到这里,执行目标类的main()方法
return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,
parsedArgs.mRemainingArgs, null /* classLoader */);
} else {
return ZygoteInit.childZygoteInit(parsedArgs.mTargetSdkVersion,
parsedArgs.mRemainingArgs, null /* classLoader */);
}
}
}
进行子进程的操作,最终获得需要执行的 ActivityThread 的 main(),zygoteInit 进行一些环境的初始化、启动 Binder 进程等操作.
public static final Runnable zygoteInit(int targetSdkVersion, String[] argv,
ClassLoader classLoader) {
RuntimeInit.commonInit(); //初始化运行环境
ZygoteInit.nativeZygoteInit(); //启动Binder线程池
//调用程序入口函数
return RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader);
}
把之前传来的 “android.app.ActivityThread” 传递给 findStaticMain:
protected static Runnable applicationInit(int targetSdkVersion, String[] argv,
ClassLoader classLoader) {
........
// startClass: 如果AMS通过socket传递过来的是 ActivityThread
return findStaticMain(args.startClass, args.startArgs, classLoader);
}
通过反射,拿到 ActivityThread 的 main() 方法:
protected static Runnable findStaticMain(String className, String[] argv,
ClassLoader classLoader) {
Class<?> cl;
try {
cl = Class.forName(className, true, classLoader);
} catch (ClassNotFoundException ex) {
throw new RuntimeException(
"Missing class when invoking static main " + className,
ex);
}
Method m;
try {
m = cl.getMethod("main", new Class[] {
String[].class });
} catch (NoSuchMethodException ex) {
throw new RuntimeException(
"Missing static main on " + className, ex);
} catch (SecurityException ex) {
throw new RuntimeException(
"Problem getting static main on " + className, ex);
}
int modifiers = m.getModifiers();
if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {
throw new RuntimeException(
"Main method is not public and static on " + className);
}
return new MethodAndArgsCaller(m, argv);
}
把反射得来的 ActivityThread main()入口返回给 ZygoteInit 的 main,通过 caller.run() 进行调用:
static class MethodAndArgsCaller implements Runnable {
/** method to call */
private final Method mMethod;
/** argument array */
private final String[] mArgs;
public MethodAndArgsCaller(Method method, String[] args) {
mMethod = method;
mArgs = args;
}
//调用ActivityThread的main()
public void run() {
try {
mMethod.invoke(null, new Object[] {
mArgs });
} catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
} catch (InvocationTargetException ex) {
Throwable cause = ex.getCause();
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
} else if (cause instanceof Error) {
throw (Error) cause;
}
throw new RuntimeException(ex);
}
}
}
zygote fork 出了 Launcher 进程,并把接下来的 Launcher 启动任务交给了 ActivityThread 来进行,接下来我们就从 ActivityThread main() 来分析 Launcher 的创建过程。
调用栈如下:
public static void main(String[] args) {
// 安装选择性的系统调用拦截
AndroidOs.install();
........
//主线程处理
Looper.prepareMainLooper();
........
//之前SystemServer调用attach传入的是true,这里到应用进程传入false就行
ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);
........
//一直循环,如果退出,说明程序关闭
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
主线程处理, 创建 ActivityThread 对象,调用 attach 进行处理,最终进入 Looper 循环,接着调用 ActivityThread 的 attach 进行处理
private void attach(boolean system, long startSeq) {
sCurrentActivityThread = this;
mSystemThread = system;
if (!system) {
//应用进程启动,走该流程
........
RuntimeInit.setApplicationObject(mAppThread.asBinder());
//获取AMS的本地代理类
final IActivityManager mgr = ActivityManager.getService();
try {
//通过Binder调用AMS的attachApplication方法
mgr.attachApplication(mAppThread, startSeq);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
........
} else {
//通过system_server启动ActivityThread对象
........
}
// 为 ViewRootImpl 设置配置更新回调,
//当系统资源配置(如:系统字体)发生变化时,通知系统配置发生变化
ViewRootImpl.ConfigChangedCallback configChangedCallback
= (Configuration globalConfig) -> {
synchronized (mResourcesManager) {
........
}
};
ViewRootImpl.addConfigCallback(configChangedCallback);
}
public final void attachApplication(IApplicationThread thread, long startSeq) {
synchronized (this) {
//通过Binder获取传入的pid信息
int callingPid = Binder.getCallingPid();
final int callingUid = Binder.getCallingUid();
final long origId = Binder.clearCallingIdentity();
attachApplicationLocked(thread, callingPid, callingUid, startSeq);
Binder.restoreCallingIdentity(origId);
}
}
private final boolean attachApplicationLocked(IApplicationThread thread,
int pid, int callingUid, long startSeq) {
........
//如果当前的Application记录仍然依附到之前的进程中,则清理掉
if (app.thread != null) {
handleAppDiedLocked(app, true, true);
}
//mProcessesReady这个变量在AMS的 systemReady 中被赋值为true,
//所以这里的normalMode也为true
boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
........
//上面说到,这里为true,进入StackSupervisor的attachApplication方法
//去真正启动Activity
if (normalMode) {
........
//调用ATM的attachApplication(),最终层层调用到
//ActivityStackSupervisor.java的 realStartActivityLocked()
didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
........
}
........
return true;
}
清除一些无用的记录,最终调用 ActivityStackSupervisor.java 的 realStartActivityLocked(),进行 Activity 的启动.
真正准备去启动 Activity,通过 clientTransaction.addCallback 把 LaunchActivityItem 的 obtain 作为回调参数加进去,再调用 ClientLifecycleManager.scheduleTransaction() 得到 LaunchActivityItem 的 execute() 方法进行最终的执行,参考上面的第三阶段的调用栈流程.
调用栈如下:
boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
boolean andResume, boolean checkConfig) throws RemoteException {
// 直到所有的 onPause() 执行结束才会去启动新的 activity
if (!mRootActivityContainer.allPausedActivitiesComplete()) {
........
return false;
}
try {
// Create activity launch transaction.
// 添加 LaunchActivityItem
final ClientTransaction clientTransaction = ClientTransaction.obtain(
proc.getThread(), r.appToken);
//LaunchActivityItem.obtain(new Intent(r.intent)作为回调参数
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.icicle, r.persistentState, results, newIntents,
dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(),
r.assistToken));
........
// 设置生命周期状态
final ActivityLifecycleItem lifecycleItem;
if (andResume) {
lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
} else {
lifecycleItem = PauseActivityItem.obtain();
}
clientTransaction.setLifecycleStateRequest(lifecycleItem);
// 调用 ClientLifecycleManager.scheduleTransaction()
// 得到上面addCallback的LaunchActivityItem的execute()方法
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
} catch (RemoteException e) {
if (r.launchFailed) {
// 第二次启动失败,finish activity
stack.requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
"2nd-crash", false);
return false;
}
// 第一次失败,重启进程并重试
r.launchFailed = true;
proc.removeActivity(r);
throw e;
}
} finally {
endDeferResume();
}
........
return true;
}
[TransactionExecutor.java]
public void execute(ClientTransaction transaction) {
........
// 执行 callBack,参考上面的调用栈,执行回调方法,
//最终调用到ActivityThread的handleLaunchActivity()
executeCallbacks(transaction);
// 执行生命周期状态
executeLifecycleState(transaction);
mPendingActions.clear();
}
执行之前 realStartActivityLocked() 中的 clientTransaction.addCallback.
[ActivityThread.java]
public Activity handleLaunchActivity(ActivityClientRecord r,
PendingTransactionActions pendingActions, Intent customIntent) {
........
//初始化WindowManagerGlobal
WindowManagerGlobal.initialize();
........
//调用performLaunchActivity,来处理Activity
final Activity a = performLaunchActivity(r, customIntent);
........
return a;
}
主要干了两件事,第一件:初始化 WindowManagerGlobal.第二件:调用 performLaunchActivity 方法.
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
// 获取 ComponentName
ComponentName component = r.intent.getComponent();
........
// 获取 Context
ContextImpl appContext = createBaseContextForActivity(r);
Activity activity = null;
try {
// 反射创建 Activity
java.lang.ClassLoader cl = appContext.getClassLoader();
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
StrictMode.incrementExpectedActivityCount(activity.getClass());
r.intent.setExtrasClassLoader(cl);
r.intent.prepareToEnterProcess();
if (r.state != null) {
r.state.setClassLoader(cl);
}
} 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);
if (customIntent != null) {
activity.mIntent = customIntent;
}
........
int theme = r.activityInfo.getThemeResource();
if (theme != 0) {
// 设置主题
activity.setTheme(theme);
}
activity.mCalled = false;
// 执行 onCreate()
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
........
r.activity = activity;
}
//当前状态为ON_CREATE
r.setState(ON_CREATE);
........
} catch (SuperNotCalledException e) {
throw e;
} catch (Exception e) {
........
}
return activity;
}
获取 ComponentName、Context,反射创建 Activity,设置 Activity 的一些内容,比如主题等; 最终调用 callActivityOnCreate() 来执行 Activity 的 onCreate() 方法.
public void callActivityOnCreate(Activity activity, Bundle icicle,
PersistableBundle persistentState) {
prePerformCreate(activity); //activity onCreate的预处理
activity.performCreate(icicle, persistentState);//执行onCreate()
postPerformCreate(activity); //activity onCreate创建后的一些信息处理
}
callActivityOnCreate 先执行 activity onCreate 的预处理,再去调用 Activity 的 onCreate,最终完成 Create 创建后的内容处理.
final void performCreate(Bundle icicle, PersistableBundle persistentState) {
........
if (persistentState != null) {
onCreate(icicle, persistentState);
} else {
onCreate(icicle);
}
........
}
performCreate() 主要调用 Activity 的 onCreate(),至此,看到了我们最熟悉的 Activity 的 onCreate(),Launcher 的启动完成,Launcher 被真正创建起来。
看到 onCreate() 后,就进入到我们最熟悉的 Activity 的入口,Launcher 的启动告一段落。至此 Launcher 的整个启动流程我们基本分析完毕。
Launcher 的启动经过了三个阶段: