Instrumentation源码阅读方法可参考:Android源码阅读技巧
SDK版本名称: Pie
API Level: 28
一、源码调用时序图
1. Activity的启动流程
说明:其中ActivityThread
中执行的scheduleTransaction
方法在其父类ClientTransactionHandler
中,发送了ActivityThread.H.EXECUTE_TRANSACTION
,ActivityThread
接收后执行了LaunchActivityItem#execute()
2.ActivityManagerService的启动流程
说明:其中RunnableInit
通过类名反射了main
方法,封装成Runnable
返回,最终在ZygoteInit#main
中执行run()
。
3.ActivityThread的启动流程
说明:图中省略了ZygoteConnection
获取MethodAndArgsCaller
的步骤,其步骤可参加ActivityManagerService
的启动流程,也是经过WrapperInit
拿到的。
二、流程总结
-
ZygoteInit#main
方法中启动一个SystemServer
和一个ZygoteServer
。 -
SystemServer
中通过SystemServiceManager
执行onStart()
的方式启动了ActivityManagerService
,使用ServiceManager
对其进行持久化管理。 -
ZygoteServer
中启动了一个名为“zygote”的LocalSocket
类型的socket服务。使用死循环去处理socket链接。 - 应用没有启动时,从Launcher进入应用,
Activity
中的startActivity()
方法最终调用了ActivityManagerService#startProcessLocked
。 - 这个方法中将
ActivityThread
的类名参数通过socket链接到ZygoteInit
中启动的ZygoteServer
。 -
ZygoteServer
死循环中得到参数后,通过ZygoteConnection#processOneCommand
返回一个MethodAndArgsCaller
类型的Runnable,在ZygoteInit#main
中执行。
(26版本会在ZygoteInit#main
方法中捕获MethodAndArgsCaller
类型的异常,然后捕获执行。两种写法的目的都是为了清除方法调用的堆栈信息) -
ActivityThread#main
方法中调用其attach
方法,将创建好的ApplicationThread
传给ActivityManagerService#
,AMS保留参数给ProcessRecord
后续使用。 - 应用已经启动时,
Activity
中的startActivity()
方法调用了ActivityManagerService#startActivityAsUser
,执行ActivityStarter#execute
- 这个方法最终调用
ActivityStackSupervisor#realStartActivityLocked
,以ActivityThread.mAppThread
为参数创建LaunchActivityItem
。然后执行AcitivityThread#scheduleTransaction
方法,发送ActivityThread.H.EXECUTE_TRANSACTION
。 -
ActivityThread
接收到消息后执行LaunchActivityItem#execute
,调用ActivityThread#handleLaunchActivity
,最终调用ActivityThread#performLaunchActivity
。 -
performLaunchActivity()
方法通过Instrumentation#newActivity
得到要启动的Activity,然后调用其attach()
方法。 - 而后,会调用
Instrumentation#callActivityOnCreate
,最终调用到Activity#onCreate
三、相关文章:
- 谁调用了Android应用的main函数
- 源码分析 — ActivityThread(一)之main()的调用 (Android应用进程的孵化)
- 源码分析 — Activity的启动流程 (这个时序图画的很好,推荐!)**
- Android设计模式(四)续:Activity的onCreate是怎么调用的
- Activity 启动时序图
- ActivityThread.main()入口调用流程
四、流程记录
- 代码跟踪记录,只保留了关键代码,其余代码用
...
替代。- java类名可点击,将跳转到Android社区的sdk源代码文件。
- 跟踪记录的意义在于,在需要研究流程中某个环节细节问题时,可以快速定位。
1. android.app.Activity.java
private Instrumentation mInstrumentation;
public void startActivity(...) {
...
startActivityForResult(...);
...
}
public void startActivityForResult(...) {
...
mInstrumentation.execStartActivity(...);
...
}
final void performCreate(...) {
...
onCreate(...);
...
}
2. android.app.Instrumentation.java
public ActivityResult execStartActivity(...) {
...
int result = ActivityManager.getService().startActivity(...)
...
}
public void callActivityOnCreate(...) {
...
activity.performCreate(...);
...
}
3. android.app.ActivityManager.java
private static final Singleton IActivityManagerSingleton = () -> {
final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
...
return am;
};
public static IActivityManager getService() {
return IActivityManagerSingleton.get();
}
4. android.os.ServiceManager.java
public static IBinder getService(String name) {
...
IBinder service = sCache.get(name);
...
}
public static void initServiceCache(Map cache) {
...
sCache.putAll(cache);
}
5. com.android.server.am.ActivityStartController.java
ActivityStartController(ActivityManagerService service) {
this(...,new DefaultFactory(..)));
}
@VisibleForTesting
ActivityStartController(...,Factory factory) {
...
mFactory = factory;
...
}
ActivityStarter obtainStarter(...) {
return mFactory.obtain().setIntent(intent).setReason(reason);
}
6. com.android.server.am.ActivityStarter.java
private ActivityStack mTargetStack;
static class DefaultFactory implements Factory {
...
public ActivityStarter obtain() {
...
return starter;
}
...
}
int execute() {
...
if (mRequest.mayWait) {
return startActivityMayWait(...);
} else {
return startActivity(...);
}
...
}
private int startActivityMayWait(...){
...
int res = startActivity(...);
...
}
private int startActivity(...){
...
result = startActivityUnchecked(...)
...
}
private int startActivityUnchecked(...){
...
mTargetStack.startActivityLocked(...);
...
}
7. com.android.server.am.ActivityStack.java
protected final ActivityStackSupervisor mStackSupervisor;
void startActivityLocked(...){
...
ensureActivitiesVisibleLocked(...);
...
}
final void ensureActivitiesVisibleLocked(...){
...
if (makeVisibleAndRestartIfNeeded(...)){
...
}
...
}
private boolean makeVisibleAndRestartIfNeeded(...){
...
mStackSupervisor.startSpecificActivityLocked(...);
...
}
8. com.android.server.am.ActivityStackSupervisor.java
final ActivityManagerService mService;
void startSpecificActivityLocked(...){
...
realStartActivityLocked(...);
...
mService.startProcessLocked(...);
...
}
final boolean realStartActivityLocked(...){
...
clientTransaction = ClientTransaction.obtain(app.thread,...);
clientTransaction.addCallback(LaunchActivityItem.obtain(...));
...
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
...
}
9. com.android.server.am.ClientLifecycleManager.java
void scheduleTransaction(...){
...
transaction.schedule();
...
}
10. android.app.servertransaction.ClientTransaction.java
private List mActivityCallbacks;
private IApplicationThread mClient;
public void addCallback(...) {
...
mActivityCallbacks.add(activityCallback);
}
public void schedule() throws RemoteException {
mClient.scheduleTransaction(this);
}
public static ClientTransaction obtain(IApplicationThread client, ...) {
...
instance.mClient = client;
...
return instance;
}
11. com.android.internal.os.ZygoteInit.java
public static void main(String argv[]) {
...
Runnable r = forkSystemServer(...);
...
r.run();
...
caller = zygoteServer.runSelectLoop(abiList);
...
caller.run();
}
private static Runnable forkSystemServer(...) {
String args[] = {
...
"com.android.server.SystemServer",
};
parsedArgs = new ZygoteConnection.Arguments(args);
...
pid = Zygote.forkSystemServer(...);
...
return handleSystemServerProcess(parsedArgs);
}
private static Runnable handleSystemServerProcess(...){
...
WrapperInit.execApplication(...);
...
}
public static final Runnable zygoteInit(...) {
...
return RuntimeInit.applicationInit(...);
}
static final Runnable childZygoteInit(...) {
...
return RuntimeInit.findStaticMain(...);
}
12. com.android.internal.os.WrapperInit.java
@Override
public static void execApplication(...) {
...
command.append(" '--nice-name=").append(niceName).append("'");
...
Zygote.execShell(command.toString());
}
13. com.android.internal.os.Zygote.java
public static int forkSystemServer(...) {
VM_HOOKS.preFork();
int pid = nativeForkSystemServer(...);
...
VM_HOOKS.postForkCommon();
return pid;
}
public static void execShell(String command) {
String[] args = { "/system/bin/sh", "-c", command };
...
Os.execv(args[0], args);
...
}
14. com.android.server.SystemServer.java
public static void main(String[] args) {
new SystemServer().run();
}
private void run() {
...
mSystemServiceManager = new SystemServiceManager(mSystemContext);
...
startBootstrapServices();
...
startOtherServices();
...
}
private void startBootstrapServices() {
...
mActivityManagerService = mSystemServiceManager.startService(...)...;
...
mPackageManagerService = PackageManagerService.main(...);
...
}
private void startOtherServices() {
...
wm = WindowManagerService.main(...);
...
mActivityManagerService.setWindowManager(wm);
...
mActivityManagerService.systemReady(...);
...
}
15. com.android.server.SystemServiceManager.java
public void startService(...) {
...
service.onStart();
...
}
16. android.os.Process.java
public static final String ZYGOTE_SOCKET = "zygote";
public static final ZygoteProcess zygoteProcess =
new ZygoteProcess(ZYGOTE_SOCKET, SECONDARY_ZYGOTE_SOCKET);
public static final ProcessStartResult start(...) {
...
return zygoteProcess.start(...);
}
17. android.os.ZygoteProcess.java
public final Process.ProcessStartResult start(...) {
...
return startViaZygote(...);
...
}
private Process.ProcessStartResult startViaZygote(...){
...
zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi),...);
...
}
private ZygoteState openZygoteSocketIfNeeded(...){
...
... = ZygoteState.connect(mSocket);
...
}
public static class ZygoteState {
...
public static ZygoteState connect(LocalSocketAddress address) ... {
...
zygoteSocket.connect(address);
...
}
}
18. com.android.internal.os.ZygoteConnection.java
Runnable processOneCommand(ZygoteServer zygoteServer) {
...
return handleChildProc(...);
...
}
private Runnable handleChildProc(...) {
...
if (...) {
WrapperInit.execApplication(...);
throw new IllegalStateException(...);
} else {
if (!isZygote) {
return ZygoteInit.zygoteInit(...);
} else {
return ZygoteInit.childZygoteInit(...);
}
}
...
}
19. com.android.internal.os.RuntimeInit.java
protected static Runnable applicationInit(...) {
...
return findStaticMain(...);
}
protected static Runnable findStaticMain(...) {
return new MethodAndArgsCaller(...);
}
static class MethodAndArgsCaller implements Runnable {
...
public void run() {
...
mMethod.invoke(null, new Object[] { mArgs });
...
}
...
}
20. com.android.internal.os.ZygoteServer.java
Runnable runSelectLoop(String abiList) {
...
ZygoteConnection connection = peers.get(i);
final Runnable command = connection.processOneCommand(this);
...
}
21. com.android.server.am.ActivityManagerService.java
public final int startActivity(...) {
return startActivityAsUser(...);
}
public final int startActivityAsUser(...) {
return mActivityStartController.obtainStarter(...)
....
.execute();
}
private final boolean startProcessLocked(...) {
...
final String entryPoint = "android.app.ActivityThread";
...
return startProcessLocked(..., entryPoint, ...);
}
private boolean startProcessLocked(..., String entryPoint,...){
...
final ProcessStartResult startResult = startProcess(...);
...
}
private ProcessStartResult startProcess(...) {
...
startResult = Process.start(entryPoint,...);
...
}
22. android.app.ActivityThread.java
public final void bindApplication(...){
...
ServiceManager.initServiceCache(services);
...
}
private Activity performLaunchActivity(...) {
...
mInstrumentation.callActivityOnCreate(...);
...
}
public Activity handleLaunchActivity(...){
...
final Activity a = performLaunchActivity(...);
...
}