文章目录
- Android应用程序启动源码分析
- 一、启动流程
- 二、Launcher通知AndroidOS(用户点击图标)
- 2.1 Activity.java
- 2.2 Instrumentation.java
- 2.3 ActivityTaskManagerService.java
- 2.4 ActivityStarter.java
- 2.5 RootWindowContainer.java
- 2.5.1 Task.java
- 2.5.2 TaskFragment.java
- 2.6 再次回到ActivityTaskManagerService.java
- 2.7 ActivityManagerService.java
- 2.7.1 ProcessList.java
- 2.8 ZygoteProcess.java
- 三、Activity进程创建(Zygote进程fork)
- 3.1 Zygote简介
- 3.2 ZygoteInit.java
- 3.3 ZygoteServer.java
- 3.4 ZygoteConnection.java
- 3.5 再次回到ZygoteInit.java
- 3.6 RuntimeInit.java
- 四、初始化Application实例
- 4.1 ActivityThread.java
- 4.2 ActivityManagerService.java
- 4.3 再次回到ActivityThread.java
- 4.4 LoadedApk.java
- 4.5 Instrumentation.java
- 五、启动第一个Activity
- 5.1 ActivityManagerService.java
- 5.2 ActivityTaskManagerService.java
- 5.3 RootWindowContainer.java
- 5.3.1 Task.java
- 5.4 ActivityTaskSupervisor.java
- 5.4.1 ClientLifecycleManager.java
- 5.4.2 ClientTransaction.java
- 5.5 回到ActivityThread.java
- 5.5.1 ClientTransactionHandler.java
- 5.5.2 ActivityThread的内部Handler类H处理消息
- 5.5.3 TransactionExecutor.java
- 5.5.4 LaunchActivityItem.java
- 5.6 回到ActivityThread
- 5.6.1 Instrumentation.java
- 5.6.2 回到ActivityThread的performLaunchActivity方法
- 5.6.3 Instrumentation的callActivityOnCreate方法
- 5.7 Activity.java
- 5.7.1 onCreate方法
- 5.7.2 onStart方法
- 5.7.2.1 TransactionExecutor.java
- 5.7.2.2 ActivityResultItem.java
- 5.7.2.3 ActivityThread的handleResumeActivity方法
- 5.7.2.4 Activity的performStart方法
- 5.7.2.5 Instrumentation的callActivityOnStart方法
- 5.7.3 onResume方法
- 5.7.3.1 Activity的performResume方法
- 5.7.3.2 Instrumentation的callActivityOnResume方法
- 六、 后续工作
Android应用程序启动源码分析
在Android桌面(Launcher)源码分析中介绍了Android的桌面程序Launcher是如何响应用户点击事件并启动App的,这篇文章继续介绍App在Android系统层的启动流程。
一、启动流程
二、Launcher通知AndroidOS(用户点击图标)
2.1 Activity.java
frameworks/base/core/java/android/app/Activity.java 源码地址
- 在Android桌面Launcher源码分析中提到
Launcher
最终通过frameworks/base/core/java/android/app/Activity.java
中的startActivity方法启动了对应的应用程序。 startActivity
方法是通过调用startActivityForResult方法来实现的。startActivityForResult
方法最终调用了/frameworks/base/core/java/android/app/Instrumentation.java
的execStartActivity方法
public class Activity {@Overridepublic void startActivity(Intent intent) {this.startActivity(intent, null);}@Overridepublic void startActivity(Intent intent, @Nullable Bundle options) {if (options != null) {startActivityForResult(intent, -1, options);} else {startActivityForResult(intent, -1);}}@Overridepublic void startActivityForResult(...) {if (mParent == null) {options = transferSpringboardActivityOptions(options);// 调用Instrumentation的execStartActivity方法Instrumentation.ActivityResult ar =mInstrumentation.execStartActivity(...);}}}
2.2 Instrumentation.java
frameworks/base/core/java/android/app/Instrumentation.java 源码地址
Instrumentation.java
中的execStartActivity方法是Activity启动流程的关键。- execStartActivity方法通过ActivityTaskManager.getService().startActivity方法与系统服务进行通信.
// Instrumentation中有多个execStartActivity同名方法,注意是target的类型为Activity的方法
public ActivityResult execStartActivity(Context who, IBinder contextThread, IBinder token, Activity target,Intent intent, int requestCode, Bundle options) {// ActivityTaskManager.getService()获取到ActivityTaskManagerService的实例对象// 调用ActivityTaskManagerService.startActivityint result = ActivityTaskManager.getService().startActivity(...);
}
2.3 ActivityTaskManagerService.java
/frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java 源码地址
ActivityTaskManagerService
是一个系统服务,负责管理Activity的启动。- startActivity方法调用了startActivityAsUser方法
- startActivityAsUser方法通过
ActivityStartController
的obtainStarter方法获取了ActivityStarter
对象实例,并调用ActivityStarter
的execute
方法
public final int startActivity(...) {// 调用startActivityAsUser方法return startActivityAsUser(...);
}public final int startActivityAsUser(...) {// ActivityStartController的obtainStarter获取了ActivityStarter对象return getActivityStartController().obtainStarter(intent, "startActivityAsUser")... // 构造参数.execute();
}
2.4 ActivityStarter.java
/frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java 源码地址
- 在
ActivityStarter
中最终会调用RootWindowContainer
的resumeFocusedTasksTopActivities方法
int execute() {// 调用executeRequest方法res = executeRequest(mRequest);
}private int executeRequest(Request request) {// 创建ActivityRecord对象final ActivityRecord r = new ActivityRecord.Builder(mService).setCaller(callerApp)... // 构造参数.build();// 调用startActivityUnchecked方法mLastStartActivityResult = startActivityUnchecked(...);
}private int startActivityUnchecked(...) {// 调用startActivityInnerresult = startActivityInner(...);
}int startActivityInner(...) {// 调用RootWindowContainer的resumeFocusedTasksTopActivities方法mRootWindowContainer.resumeFocusedTasksTopActivities(...);
}
2.5 RootWindowContainer.java
/frameworks/base/services/core/java/com/android/server/wm/RootWindowContainer.java 源码地址
RootWindowContainer
是WindowManagerService的主要组成部分之一,是一个管理窗口的容器。- 调用
Task
和TaskFragment
将前台程序Pause,为新的应用程序启动做准备。 - 在resumeFocusedTasksTopActivities中调用
Task
的resumeTopActivityUncheckedLocked方法。
private boolean resumeFocusedTasksTopActivities(...) {// 调用Task的resumeTopActivityUncheckedLocked方法result = targetRootTask.resumeTopActivityUncheckedLocked(...);
}
2.5.1 Task.java
/frameworks/base/services/core/java/com/android/server/wm/Task.java 源码地址
- 在
Task
最终调用TaskFragment
的resumeTopActivity方法
@GuardedBy("mService")
boolean resumeTopActivityUncheckedLocked(...) {// 调用resumeTopActivityInnerLockedsomeActivityResumed = resumeTopActivityInnerLocked(...);
}@GuardedBy("mService")
private boolean resumeTopActivityInnerLocked(...) {final TaskFragment topFragment = topActivity.getTaskFragment();// 调用TaskFragment的resumeTopActivityresumed[0] = topFragment.resumeTopActivity(...););return resumed[0];
}
2.5.2 TaskFragment.java
/frameworks/base/services/core/java/com/android/server/wm/TaskFragment.java 源码地址
- 在
TaskFragment
最终调用ActivityTaskManagerService
的startProcessAsync方法
final boolean resumeTopActivity(...) {// 暂停当前窗口的Aciticity,可参见源码...// 调用ActivityTaskManagerService的startProcessAsync方法创建新的Activity
ActivityTaskManagerService的startProcessAsync方法mAtmService.startProcessAsync(...);
}
2.6 再次回到ActivityTaskManagerService.java
/frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java 源码地址
- 处理完窗口容器数据以后(核心工作是将前台程序Pause),再次回到了
ActivityTaskManagerService
- 在startProcessAsync方法发送异步消息,调用
ActivityManagerInternal
的startProcess方法 ActivityManagerInternal
的实现类是ActivityManagerService
// mAmInternal的获取方法,注册方法在ActivityManagerService中(下一小节2.8做介绍)
mAmInternal = LocalServices.getService(ActivityManagerInternal.class);void startProcessAsync(...) {// PooledLambda会自动调用mAmInternal(ActivityManagerInternal)的startProcess方法final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess, mAmInternal, ...);mH.sendMessage(m);
}
- ActivityManagerInternal是一个抽象类,具体实现在
ActivityManagerService.java
中实现
2.7 ActivityManagerService.java
/frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java 源码地址
- 在
ActivityManagerService
最终调用ProcessList
的startProcessLocked方法
public class ActivityManagerService extends IActivityManager.Stub {// 初始化LocalService(ActivityManagerInternal)private final ActivityManagerInternal mInternal = new LocalService();public void init() {// 在LocalServices中进行注册LocalServices.addService(ActivityManagerInternal.class, mInternal);}private class LocalService extends ActivityManagerInternal {// ActivityManagerInternal 接口方法的具体实现@Overridepublic void startProcess(...) {synchronized (ActivityManagerService.this) {// 调用ActivityManagerService的startProcessLocked方法startProcessLocked(...)}}}@GuardedBy("this")final ProcessRecord startProcessLocked(...) {// 调用ProcessList的startProcessLockedreturn mProcessList.startProcessLocked(...);}
}
2.7.1 ProcessList.java
/frameworks/base/services/core/java/com/android/server/am/ProcessList.java 源码地址
- 在
ProcessList
最终调用到ZygoteProcess
的start方法
@GuardedBy("mService")
boolean startProcessLocked(ProcessRecord app, ...) {// 定义创建Activity完成后回调的入口点(重要)final String entryPoint = "android.app.ActivityThread";return startProcessLocked(hostingRecord, ...);
}@GuardedBy("mService")
boolean startProcessLocked(HostingRecord hostingRecord, ...) {// 调用startProcessfinal Process.ProcessStartResult startResult = startProcess(...);
}private Process.ProcessStartResult startProcess(...) {// 获取AppZygotefinal AppZygote appZygote = createAppZygoteForProcessIfNeeded(app);// appZygote.getProcess()获取到ChildZygoteProcess类(ZygoteProcess的子类)// 调用ZygoteProcess的start方法startResult = appZygote.getProcess().start(entryPoint,...);
}
2.8 ZygoteProcess.java
/frameworks/base/core/java/android/os/ZygoteProcess.java 源码地址
- 在
ZygoteProcess
发送消息给Zygote进程
,通过Zygote进程
创建新的activity进程
public final Process.ProcessStartResult start(...) {// 调用startViaZygotereturn startViaZygote(...)
}private Process.ProcessStartResult startViaZygote(...) {// 通过openZygoteSocketIfNeeded(abi)打开一个到Zygote进程的套接字连接(Socket)。// 调用zygoteSendArgsAndGetResultreturn zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi),zygotePolicyFlags,argsForZygote);
}@GuardedBy("mLock")
private Process.ProcessStartResult zygoteSendArgsAndGetResult(...) {// 调用attemptZygoteSendArgsAndGetResultreturn attemptZygoteSendArgsAndGetResult(...);
}private Process.ProcessStartResult attemptZygoteSendArgsAndGetResult(...) {try {// 创建Zygote套接字的输入输出流final BufferedWriter zygoteWriter = zygoteState.mZygoteOutputWriter;final DataInputStream zygoteInputStream = zygoteState.mZygoteInputStream;// 发送消息给 Zygote 进程zygoteWriter.write(msgStr);zygoteWriter.flush();// 读取 Zygote 进程返回的结果Process.ProcessStartResult result = new Process.ProcessStartResult();result.pid = zygoteInputStream.readInt();result.usingWrapper = zygoteInputStream.readBoolean();// 检查 PID 是否有效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);}
}
三、Activity进程创建(Zygote进程fork)
在Android启动过程-万字长文(Android14)介绍了Zygote进程(孵化器进程)
3.1 Zygote简介
- Zygote进程是一个用户进程,由init进程(1号进程)fork而来。
- Zygote进程通过fork的方式创建新的应用程序进程。
- Zygote进程的入口点是
ZygoteInit
类中的main方法。
下面将简单介绍在Zygote进程的代码流转。
3.2 ZygoteInit.java
Android14的ZygoteInit源码地址
Zygote
进程是在Android系统启动过程中创建的,创建完成后会通过ZygoteServer
来监听消息
public static void main(String argv[]) {ZygoteServer zygoteServer = new ZygoteServer();...// 启动Zygote服务器,循环监听消息caller = zygoteServer.runSelectLoop(abiList);if (caller != null) {// 有新的消息就执行对应Runnable代码caller.run();}...
}
3.3 ZygoteServer.java
Android14的ZygoteServer源码地址
- 在
ZygoteServer
获取到消息后会调用ZygoteConnection
的processCommand方法
Runnable runSelectLoop(String abiList) {while (true) {// 使用 select 监听套接字StructPollfd[] pollFDs = new StructPollfd[socketFDs.size()];if (pollIndex == 0) {// 接收到新的连接ZygoteConnection newPeer = acceptCommandPeer(abiList);peers.add(newPeer);socketFDs.add(newPeer.getFileDescriptor());} else {// 处理已有连接的请求ZygoteConnection connection = peers.get(pollIndex);final Runnable command = connection.processCommand(this, multipleForksOK);}}
}
3.4 ZygoteConnection.java
Android14的ZygoteConnection源码地址
ZygoteConnection
的processCommand方法最终调用ZygoteInit
的zygoteInit方法
Runnable processCommand(ZygoteServer zygoteServer, boolean multipleOK) {...// 调用Zygote的forkAndSpecialize方法fork出Acitivity的进程pid = Zygote.forkAndSpecialize(...);if (pid == 0) {// 在子进程中,即创建出来的应用程序所在进程return handleChildProc(parsedArgs, childPipeFd,parsedArgs.mStartChildZygote);} else {// 在父线程中,pid为创建好的子进程的idhandleParentProc(pid, serverPipeFd);return null;}
}private void handleParentProc(int pid, FileDescriptor serverPipeFd) {// 通过套接字Socket将子进程的 PID 返回给请求方(ActivityManagerService)os.writeInt(pid);
}private Runnable handleChildProc(...) {// 子进程负责应用程序后续的初始化工作ZygoteInit.zygoteInit(...)
}
- fork系统调用会创建一个新的进程(子进程)。在调用fork后,父进程和子进程(新创建出来的进程)会各自执行后续的代码。
- 在父进程中,fork返回子进程的PID。这是一个正整数,表示新创建的子进程的进程ID。
- 在子进程中(新进程),fork 返回 0。这表示当前进程是新创建的子进程。
- 应用程序(App)的进程就是新创建的子进程
3.5 再次回到ZygoteInit.java
Android14的ZygoteInit源码地址
- 调用
RuntimeInit.applicationInit
方法,进行应用程序的初始化过程
public static Runnable zygoteInit(...) {// 常见的初始化工作,例如设置系统属性、初始化默认的未捕获异常处理器等RuntimeInit.commonInit();// Zygote相关的初始化工作。这个初始化过程在C/C++层面进行,设置了必要的Zygote运行环境ZygoteInit.nativeZygoteInit();// 调用RuntimeInit.applicationInit方法,进行应用程序的初始化过程return RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv, classLoader);
}
3.6 RuntimeInit.java
Android14的RuntimeInit源码地址
- 在
RuntimeInit
的applicationInit方法完成初始化工作后,通过反射的方式,调用android.app.ActivityThread
的main方法 - 参数列表中的startClass即
2.9 ProcessList.java
源码中的entryPoint(android.app.ActivityThread
)
protected static Runnable applicationInit(...) {// 查找并返回应用程序的主方法return findStaticMain(args.startClass, args.startArgs, classLoader);
}private static Runnable findStaticMain(...) {// 反射得到android.app.ActivityThread类cl = Class.forName(className, true, classLoader);// 反射获取main方法m = cl.getMethod("main", new Class[] { String[].class });// 返回可被执行的Runnable对象return new MethodAndArgsCaller(m, argv);
}
四、初始化Application实例
通过Zygote进程
fork出应用程序的进程后,下一步就是创建整个应用程序的Application实例
4.1 ActivityThread.java
Android14的ActivityThread源码地址
- 创建应用程序的ActivityThread实例
- 创建应用程序的Application实例
- 创建应用程序的Looper循环
public static void main(String[] args) {// 初始化主线模块initializeMainlineModules();// 创建MainLooperLooper.prepareMainLooper();// 创建ActivityThreadActivityThread thread = new ActivityThread();// 创建应用程序Application实例thread.attach(false, startSeq);if (sMainThreadHandler == null) {sMainThreadHandler = thread.getHandler();}// 循环监听消息Looper.loop();
}@UnsupportedAppUsage
private void attach(boolean system, long startSeq) {// 获取ActivityManagerService实例final IActivityManager mgr = ActivityManager.getService();// 调用ActivityManagerService的attachApplication方法mgr.attachApplication(mAppThread, startSeq);
}
4.2 ActivityManagerService.java
Android14的ActivityManagerService源码地址
- 在
ActivityManagerService
完成Application创建和第一个Activity的创建
@Override
public final void attachApplication(IApplicationThread thread, long startSeq) {// 调用attachApplicationLocked方法attachApplicationLocked(thread, callingPid, callingUid, startSeq);
}private void attachApplicationLocked(...) {// 调用ActivityThread的bindApplication方法创建并绑定Applicationthread.bindApplication(...)// 在结束Application创建后调用finishAttachApplicationInner启动app的第一个Activity页面,在4.5会介绍这一部分代码finishAttachApplicationInner(startSeq, callingUid, pid);
}
4.3 再次回到ActivityThread.java
Android14的ActivityThread源码地址
- 通过Handler机制完成消息的传递,正式加载apk文件
public final void bindApplication(...) {AppBindData data = new AppBindData();... // 构造data的数据// H为Handler, BIND_APPLICATION是int值sendMessage(H.BIND_APPLICATION, data);
}// ActivityThread的内部类H
class H extends Handler {public void handleMessage(Message msg) {switch (msg.what) {case BIND_APPLICATION:AppBindData data = (AppBindData)msg.obj;handleBindApplication(data);break;}}
}@UnsupportedAppUsage
private void handleBindApplication(AppBindData data) {Application app;// 最终调用LoadedApk的makeApplicationInner方法加载apk文件到内存中app = data.info.makeApplicationInner(data.restrictedBackupMode, null);// 调用Application的onCreate方法,正式进入apk执行文件mInstrumentation.callApplicationOnCreate(app);
}
4.4 LoadedApk.java
Android14的LoadedApk源码地址
private Application makeApplicationInner(...) {// 获取app的application类(在AndroidManifast.xml中定义的),没有就使用默认的android.app.ApplicationString appClass = mApplicationInfo.getCustomApplicationClassNameForProcess(myProcessName);if (forceDefaultAppClass || (appClass == null)) {appClass = "android.app.Application";}// 调用Instrumentation的newApplication方法创建Application对象app = mActivityThread.mInstrumentation.newApplication(cl, appClass, appContext);
}
4.5 Instrumentation.java
Android14的Instrumentation源码地址
- 在
Instrumentation
完成Application实例的初始化,并调用onCreate方法
// 创建Application对象
static public Application newApplication(Class<?> clazz, Context context) {// Application实例的初始化Application app = (Application)clazz.newInstance();app.attach(context);return app;
}// 调用Application的onCreate方法
public void callApplicationOnCreate(Application app) {app.onCreate();
}
五、启动第一个Activity
5.1 ActivityManagerService.java
Android14的ActivityManagerService源码地址
- 在执行完Application的onCreate方法后,我们再回到
ActivityManagerService.java
的attachApplicationLocked方法中 - 在attachApplicationLocked方法最终会调用
LocalService
的attachApplication方法来加载我们的第一个Acitivity页面 ActivityTaskManagerInternal
是定义在ActivityTaskManagerService.java
的LocalService
类
private void attachApplicationLocked(...) {// 调用ActivityThread的bindApplication方法创建并绑定Applicationthread.bindApplication(...)// 在结束Application创建后调用finishAttachApplicationInner启动app的第一个Activity页面finishAttachApplicationInner(startSeq, callingUid, pid);
}private void finishAttachApplicationInner(long startSeq, int uid, int pid) {if (normalMode) {try {// 调用`ActivityTaskManagerInternal`(即ActivityTaskManagerService.LocalService)的**attachApplication**方法来加载我们的第一个Acitivity页面didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());}}
}
5.2 ActivityTaskManagerService.java
Android14的ActivityTaskManagerService源码地址
- 在LocalService中调用
RootWindowContainer.attachApplication
方法
final class LocalService extends ActivityTaskManagerInternal {@Overridepublic boolean attachApplication(WindowProcessController wpc){// 调用RootWindowContainer的attachApplicationreturn mRootWindowContainer.attachApplication(wpc);}
}
5.3 RootWindowContainer.java
Android14的RootWindowContainer源码地址
- 最终调用
ActivityTaskSupervisor
的realStartActivityLocked方法
boolean attachApplication(WindowProcessController app) throws RemoteException {// 调用RootWindowContainer内部类AttachApplicationHelper的process方法return mAttachApplicationHelper.process(app);
}
private class AttachApplicationHelper implements Consumer<Task>, Predicate<ActivityRecord> {boolean process(WindowProcessController app) throws RemoteException {mApp = app;for (int displayNdx = getChildCount() - 1; displayNdx >= 0; --displayNdx) {// 通过/frameworks/base/services/core/java/com/android/server/wm/Task.java中的forAllRootTasks调用test方法getChildAt(displayNdx).forAllRootTasks(this);}}public boolean test(ActivityRecord r) {// 调用ActivityTaskSupervisor的realStartActivityLocked方法mTaskSupervisor.realStartActivityLocked(...)}
}
5.3.1 Task.java
/frameworks/base/services/core/java/com/android/server/wm/Task.java源码地址
boolean forAllRootTasks(Predicate<Task> callback, boolean traverseTopToBottom) {// 调用test方法return isRootTask() ? callback.test(this) : false;
}
5.4 ActivityTaskSupervisor.java
Android14的ActivityTaskSupervisor源码地址
boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,boolean andResume, boolean checkConfig) throws RemoteException {...// 创建ClientTransaction启动事务:final ClientTransaction clientTransaction = ClientTransaction.obtain(proc.getThread(), r.token);...// 添加LaunchActivityItem回调clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent...));...// 执行启动事务,调用ClientLifecycleManager的scheduleTransaction方法mService.getLifecycleManager().scheduleTransaction(clientTransaction);...}
- ClientTransaction事务对象,用于描述一系列客户端(即应用进程)需要执行的操作。
- LaunchActivityItem回调参数中包括如何启动Activity,启动所需的Intent、配置、状态等信息。
5.4.1 ClientLifecycleManager.java
Android14的ClientLifecycleManager源码地址
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {final IApplicationThread client = transaction.getClient();// 调用ClientTransaction的scheduletransaction.schedule();
}
5.4.2 ClientTransaction.java
Android14的ClientTransaction源码地址
public void schedule() throws RemoteException {// 调用mClient的scheduleTransaction方法mClient.scheduleTransaction(this);
}
- mClient是
IApplicationThread
接口,实际是ActivityThread的内部类ApplicationThread
对象。 - mClient在
ActivityTaskSupervisor的realStartActivityLocked方法
中通过ClientTransaction.obtain(proc.getThread(), r.token),具体可参考ActivityTaskSupervisor源码
5.5 回到ActivityThread.java
Android14的ActivityThread源码地址
private class ApplicationThread extends IApplicationThread.Stub {@Overridepublic void scheduleTransaction(ClientTransaction transaction) throws RemoteException {// 调用ActivityThread的scheduleTransactionActivityThread.this.scheduleTransaction(transaction);}
}
- scheduleTransaction方法实际调用的是
ActivityThread父类ClientTransactionHandler
的scheduleTransaction方法
5.5.1 ClientTransactionHandler.java
Android14的ClientTransactionHandler源码地址
void scheduleTransaction(ClientTransaction transaction) {transaction.preExecute(this);// 将事务放入消息队列中,等待主线程的处理sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}
5.5.2 ActivityThread的内部Handler类H处理消息
Android14的ActivityThread源码地址
public void handleMessage(Message msg) {switch (msg.what) {case EXECUTE_TRANSACTION:final ClientTransaction transaction = (ClientTransaction) msg.obj;mTransactionExecutor.execute(transaction);break;}
}
5.5.3 TransactionExecutor.java
Android14的TransactionExecutor源码地址
public void execute(ClientTransaction transaction) {// 执行事务中的回调和生命周期状态请求executeCallbacks(transaction);executeLifecycleState(transaction);
}public void executeCallbacks(ClientTransaction transaction) {final List<ClientTransactionItem> callbacks = transaction.getCallbacks();// 遍历事务中的所有回调项,并调用每个回调项的execute方法。for (int i = 0, size = callbacks.size(); i < size; ++i) {final ClientTransactionItem item = callbacks.get(i);item.execute(mClient, mTransactionHandler, transaction.getLifecycleStateRequest());}
}
- 每个回调项的execute方法实际就是调用
LaunchActivityItem
的execute方法
5.5.4 LaunchActivityItem.java
Android14的LaunchActivityItem源码地址
@Override
public void execute(ClientTransactionHandler client, IBinder token, PendingTransactionActions pendingActions) {client.handleLaunchActivity(new LaunchActivityItem.ActivityClientRecord(this), pendingActions, null);
}
- 调用ClientTransactionHandler即
ActivityThread
的handleLaunchActivity方法
5.6 回到ActivityThread
Android14的ActivityThread源码地址
public Activity handleLaunchActivity(ActivityClientRecord r, PendingTransactionActions pendingActions, Intent customIntent) {// 调用performLaunchActivityfinal Activity a = performLaunchActivity(r, customIntent);
}private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {// 创建activity对象activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);
}
5.6.1 Instrumentation.java
Android14的Instrumentation源码地址
public Activity newActivity(...) {// 创建ActivityActivity activity = (Activity)clazz.newInstance();...return activity;
}
5.6.2 回到ActivityThread的performLaunchActivity方法
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {// 创建activity对象activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);// activity绑定上下文Contextactivity.attach(appContext, this, getInstrumentation(), r.token,...);// 调用Instrumentation的callActivityOnCreate方法mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
}
5.6.3 Instrumentation的callActivityOnCreate方法
public void callActivityOnCreate(Activity activity, Bundle icicle) {// 调用Activity的performCreate方法activity.performCreate(icicle);
}
5.7 Activity.java
Android14的Activity源码地址
- 在Activity中实现了生命周期方法的调用逻辑
5.7.1 onCreate方法
final void performCreate(...) {// 调用onCreate方法if (persistentState != null) {onCreate(icicle, persistentState);} else {onCreate(icicle);}
}
- 绕了一大圈,最终又回到了Activity.java
- 在performCreate中调用onCreate生命周期方法
5.7.2 onStart方法
5.7.2.1 TransactionExecutor.java
- 在TransactionExecutor.java的方法execute中通过executeCallbacks创建了Activity并调用onCreate方法
- 然后在executeLifecycleState方法中调用后续的生命周期方法
public void execute(ClientTransaction transaction) {// 执行事务中的回调executeCallbacks(transaction);// 执行生命周期executeLifecycleState(transaction);
}public void executeLifecycleState(ClientTransaction transaction) {final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();if (lifecycleItem != null) {// 调用ActivityLifecycleItem的execute方法lifecycleItem.execute(transaction.getClientTransactionHandler(), token, pendingActions);}
}
ActivityResultItem
是一个抽象类- 这里实际调用的是
ActivityResultItem
的execute方法
5.7.2.2 ActivityResultItem.java
Android14的ActivityResultItem源码地址
public void execute(ClientTransactionHandler client, IBinder token,PendingTransactionActions pendingActions) {client.handleResumeActivity(token, true /* isForward */, "RESUME_ACTIVITY");
}
- 这里实际调用的是
ActivityThread
的handleResumeActivity方法
5.7.2.3 ActivityThread的handleResumeActivity方法
Android14的ActivityThread源码地址
public void handleResumeActivity(IBinder token, boolean finalStateRequest, String reason) {// 先调用ActivityThread的performStart方法performRestartActivity(r);// 再调用Activity的performResumer.activity.performResume();
}public void performRestartActivity(ActivityClientRecord r) {// 调用Activity的performStartr.activity.performStart();
}
5.7.2.4 Activity的performStart方法
Android14的Activity源码地址
final void performStart() {// 调用Instrumentation的callActivityOnStart方法mInstrumentation.callActivityOnStart(this);
}
5.7.2.5 Instrumentation的callActivityOnStart方法
Android14的Instrumentation源码地址
public void callActivityOnStart(Activity activity) {activity.onStart();
}
5.7.3 onResume方法
在5.7.2.3 ActivityThread的handleResumeActivity方法
中提到在onStart方法执行后会调用r.activity.performResume();
即Activity的performResume方法
5.7.3.1 Activity的performResume方法
Android14的Activity源码地址
final void performResume(boolean followedByPause, String reason) {mInstrumentation.callActivityOnResume(this);
}
5.7.3.2 Instrumentation的callActivityOnResume方法
Android14的Instrumentation源码地址
public void callActivityOnResume(Activity activity) {activity.onResume();
}
- 至此Activity创建完成,并完成了核心生命周期方法的创建
- 在onResume方法后,Activity进入前台,准备显示给用户
六、 后续工作
在生命周期完成后,应用程序就会被展示在屏幕上,后续的工作主要是渲染,这里做一个简单的流程说明
- Activity实例化时创建一个Window对象,默认情况下是PhoneWindow。在PhoneWindow中,有一个 DecorView,它是整个视图层次的根视图。
- 在Activity的onCreate方法中,Activity会调用setContentView方法,将布局资源加载到DecorView中
- WindowManager负责管理应用程序窗口,将DecorView添加到窗口中
- 当DecorView被添加到窗口中后。ViewRootImpl类负责视图层次结构的测量(measure)、布局(layout)和绘制(draw)
- 最终由SurfaceFlinger合成并显示在屏幕上
以上就是应用程序启动的全过程,如果对你有帮助,就一键三连呗(关注+点赞+收藏),我会持续更新更多干货~~