Instrumentation
SDK版本名称: Pie
API Level: 28
一、源码调用时序图
1. Activity的启动流程
说明:其中ActivityThread中执行的scheduleTransaction方法在其父类ClientTransactionHandler中,发送了ActivityThread.H.EXECUTE_TRANSACTION,ActivityThread接收后执行了LaunchActivityItem#execute()
Activity的启动流程.jpg
2.ActivityManagerService的启动流程
说明:其中RunnableInit通过类名反射了main方法,封装成Runnable返回,最终在ZygoteInit#main中执行run()。
ActivityManagerService的启动流程.jpg
3.ActivityThread的启动流程
说明:图中省略了ZygoteConnection获取MethodAndArgsCaller的步骤,其步骤可参加ActivityManagerService的启动流程,也是经过WrapperInit拿到的。
ActivityThread的启动流程 .jpg
二、流程总结
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
三、相关文章:
四、流程记录
代码跟踪记录,只保留了关键代码,其余代码用...替代。
java类名可点击,将跳转到Android社区的sdk源代码文件。
跟踪记录的意义在于,在需要研究流程中某个环节细节问题时,可以快速定位。
private Instrumentation mInstrumentation;
public void startActivity(...) {
...
startActivityForResult(...);
...
}
public void startActivityForResult(...) {
...
mInstrumentation.execStartActivity(...);
...
}
final void performCreate(...) {
...
onCreate(...);
...
}
public ActivityResult execStartActivity(...) {
...
int result = ActivityManager.getService().startActivity(...)
...
}
public void callActivityOnCreate(...) {
...
activity.performCreate(...);
...
}
private static final Singleton IActivityManagerSingleton = () -> {
final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
...
return am;
};
public static IActivityManager getService() {
return IActivityManagerSingleton.get();
}
public static IBinder getService(String name) {
...
IBinder service = sCache.get(name);
...
}
public static void initServiceCache(Map cache) {
...
sCache.putAll(cache);
}
ActivityStartController(ActivityManagerService service) {
this(...,new DefaultFactory(..)));
}
@VisibleForTesting
ActivityStartController(...,Factory factory) {
...
mFactory = factory;
...
}
ActivityStarter obtainStarter(...) {
return mFactory.obtain().setIntent(intent).setReason(reason);
}
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(...);
...
}
protected final ActivityStackSupervisor mStackSupervisor;
void startActivityLocked(...){
...
ensureActivitiesVisibleLocked(...);
...
}
final void ensureActivitiesVisibleLocked(...){
...
if (makeVisibleAndRestartIfNeeded(...)){
...
}
...
}
private boolean makeVisibleAndRestartIfNeeded(...){
...
mStackSupervisor.startSpecificActivityLocked(...);
...
}
final ActivityManagerService mService;
void startSpecificActivityLocked(...){
...
realStartActivityLocked(...);
...
mService.startProcessLocked(...);
...
}
final boolean realStartActivityLocked(...){
...
clientTransaction = ClientTransaction.obtain(app.thread,...);
clientTransaction.addCallback(LaunchActivityItem.obtain(...));
...
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
...
}
void scheduleTransaction(...){
...
transaction.schedule();
...
}
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;
}
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(...);
}
@Override
public static void execApplication(...) {
...
command.append(" '--nice-name=").append(niceName).append("'");
...
Zygote.execShell(command.toString());
}
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);
...
}
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(...);
...
}
public void startService(...) {
...
service.onStart();
...
}
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(...);
}
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);
...
}
}
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(...);
}
}
...
}
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 });
...
}
...
}
Runnable runSelectLoop(String abiList) {
...
ZygoteConnection connection = peers.get(i);
final Runnable command = connection.processOneCommand(this);
...
}
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,...);
...
}
public final void bindApplication(...){
...
ServiceManager.initServiceCache(services);
...
}
private Activity performLaunchActivity(...) {
...
mInstrumentation.callActivityOnCreate(...);
...
}
public Activity handleLaunchActivity(...){
...
final Activity a = performLaunchActivity(...);
...
}