盒子
盒子

从源码看安卓应用的启动过程

一般来讲安卓中的每个应用都是在一个单独的进程中运行的(当然也能使用android:process指定不同组件运行在不同进程中)。

我们在上图中可以看到,每一个进程都有一个java虚拟机(Dalvik虚拟机/ART虚拟机)实例。如果每次启动一个应用都需要启动一个新的虚拟机,然后初始化一堆的东西,那应用的启动时间将会变得无比漫长。

那有什么办法优化呢?

假设我们有一个模板进程,每次不需要重新启动,只需要重这个模板进程中拷贝一份出来,是不是就能节省一部分初始化的时间了?Zygote 进程就是这个模板进程。

Zygote是受精卵的意思,十分形象的一个比喻。app的进程就是通过fork的方式从Zygote进程克隆出来的,而且使用了写时拷贝的方法,尽可能的复用Zygote进程的资源。fork是UNIX关于进程管理的一个术语,本质是新开一个进程,但是不从磁盘加载代码,而是从内存现有进程复制一份。而写时拷贝是一直只有在修改的时候才会拷贝的策略,这里我就不详细展开他们了,有兴趣的同学可以在网上搜索一下。

说回Zygote进程,他是系统在启动的时候创建的,在启动之后会打开/dev/socket/zygote使用LocalSocket去监听启动应用进程的请求。当接收到启动请求的时候就会fork一个子进程出来:

应用进程是在 ActivityManagerService.startProcessLocked方法里面启动的:

1
2
3
4
5
6
7
private final void startProcessLocked(ProcessRecord app,  String hostingType, String hostingNameStr) {
...
Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
app.processName, uid, uid, gids, debugFlags, mountExternal,
app.info.targetSdkVersion, app.info.seinfo, null);
...
}

我们可以在Process里面看到,它的确是通过LocalSocket与Zygote进行交互的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
public class Process {
...
private static final String ZYGOTE_SOCKET = "zygote";
...
public static final ProcessStartResult start(final String processClass,
final String niceName,
int uid, int gid, int[] gids,
int debugFlags, int mountExternal,
int targetSdkVersion,
String seInfo,
String[] zygoteArgs) {
...
return startViaZygote(processClass, niceName, uid, gid, gids, debugFlags, mountExternal, targetSdkVersion, seInfo, zygoteArgs);
...
}
...
private static ProcessStartResult startViaZygote(final String processClass,
final String niceName,
final int uid, final int gid,
final int[] gids,
int debugFlags, int mountExternal,
int targetSdkVersion,
String seInfo,
String[] extraArgs)
throws ZygoteStartFailedEx {
...
return zygoteSendArgsAndGetResult(argsForZygote);
}
...
private static ProcessStartResult zygoteSendArgsAndGetResult(ArrayList<String> args) throws ZygoteStartFailedEx {
openZygoteSocketIfNeeded();
...
sZygoteWriter.write(Integer.toString(args.size())); 、
sZygoteWriter.newLine();
int sz = args.size();
for (int i = 0; i < sz; i++) {
String arg = args.get(i);
if (arg.indexOf('\n') >= 0) {
throw new ZygoteStartFailedEx("embedded newlines not allowed");
}
sZygoteWriter.write(arg);
sZygoteWriter.newLine();
}

sZygoteWriter.flush();

// Should there be a timeout on this?
ProcessStartResult result = new ProcessStartResult();
result.pid = sZygoteInputStream.readInt();
if (result.pid < 0) {
throw new ZygoteStartFailedEx("fork() failed");
}
result.usingWrapper = sZygoteInputStream.readBoolean();
...
}
...
private static void openZygoteSocketIfNeeded() throws ZygoteStartFailedEx {
...
sZygoteSocket = new LocalSocket();
sZygoteSocket.connect(new LocalSocketAddress(ZYGOTE_SOCKET,
LocalSocketAddress.Namespace.RESERVED));
...
}
}

那zygote进程通过LocalSocket监听到请求之后又做了什么呢?ZygoteInit.runSelectLoop就是用来监听LocalSocket请求我们看看源码,其实它是在一个while死循环里不断select LocalSocket消息:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
private static void runSelectLoop() throws MethodAndArgsCaller {
ArrayList<FileDescriptor> fds = new ArrayList<FileDescriptor>();
ArrayList<ZygoteConnection> peers = new ArrayList<ZygoteConnection>();
FileDescriptor[] fdArray = new FileDescriptor[4];

fds.add(sServerSocket.getFileDescriptor());
peers.add(null);

int loopCount = GC_LOOP_COUNT;
while (true) {
int index;

/*
* Call gc() before we block in select().
* It's work that has to be done anyway, and it's better
* to avoid making every child do it. It will also
* madvise() any free memory as a side-effect.
*
* Don't call it every time, because walking the entire
* heap is a lot of overhead to free a few hundred bytes.
*/
if (loopCount <= 0) {
gc();
loopCount = GC_LOOP_COUNT;
} else {
loopCount--;
}


try {
fdArray = fds.toArray(fdArray);
index = selectReadable(fdArray);
} catch (IOException ex) {
throw new RuntimeException("Error in select()", ex);
}

if (index < 0) {
throw new RuntimeException("Error in select()");
} else if (index == 0) {
ZygoteConnection newPeer = acceptCommandPeer();
peers.add(newPeer);
fds.add(newPeer.getFileDesciptor());
} else {
boolean done;
done = peers.get(index).runOnce();

if (done) {
peers.remove(index);
fds.remove(index);
}
}
}
}

接收到消息之后会调ZygoteConnection.runOnce,在这个方法里面调用了Zygote.forkAndSpecialize方法去fork一个进程,这里我们就不再深入了。我们继续跟踪下去发现他又调了ZygoteInit.invokeStaticMain:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
boolean runOnce() throws ZygoteInit.MethodAndArgsCaller {
...
pid = Zygote.forkAndSpecialize(parsedArgs.uid, parsedArgs.gid, parsedArgs.gids,
parsedArgs.debugFlags, rlimits, parsedArgs.mountExternal, parsedArgs.seInfo,
parsedArgs.niceName);
...
handleChildProc(parsedArgs, descriptors, childPipeFd, newStderr);
...
}

private void handleChildProc(Arguments parsedArgs,
FileDescriptor[] descriptors, FileDescriptor pipeFd, PrintStream newStderr)
throws ZygoteInit.MethodAndArgsCaller {
...
ZygoteInit.invokeStaticMain(cloader, className, mainArgs);
...
}

ZygoteInit.invokeStaticMain的方法比较短,我就全部复制上来了,可以看到,这里用反射的方式调用了main方法,也就是ActivityThread.main:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
static void invokeStaticMain(ClassLoader loader,
String className, String[] argv)
throws ZygoteInit.MethodAndArgsCaller {
Class<?> cl;

try {
cl = loader.loadClass(className);
} 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);
}

/*
* This throw gets caught in ZygoteInit.main(), which responds
* by invoking the exception's run() method. This arrangement
* clears up all the stack frames that were required in setting
* up the process.
*/
throw new ZygoteInit.MethodAndArgsCaller(m, argv);
}

然后就到了ActivityThread.main方法,可以看到在这个方法里面初始化了sMainThreadHandler和Looper。这个就是主线程Handler对应的Looper了:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public static void main(String[] args) {
SamplingProfilerIntegration.start();

// CloseGuard defaults to true and can be quite spammy. We
// disable it here, but selectively enable it later (via
// StrictMode) on debug builds, but using DropBox, not logs.
CloseGuard.setEnabled(false);

Environment.initForCurrentUser();

// Set the reporter for event logging in libcore
EventLogger.setReporter(new EventLoggingReporter());

Security.addProvider(new AndroidKeyStoreProvider());

Process.setArgV0("<pre-initialized>");

Looper.prepareMainLooper();

ActivityThread thread = new ActivityThread();
thread.attach(false);

if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}

AsyncTask.init();

if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}

Looper.loop();

throw new RuntimeException("Main thread loop unexpectedly exited");
}

于是乎一个应用的主线程就这样启动了,接下来就是ActivityManagerService通过Binder机制去让ActivityThread用Hander同步创建主Activity,并且调用Activity生命周期了。这部分最近有写过一篇博客《从源码看Activity生命周期》感兴趣的同学可以去看看。