一、Application启动
此处App启动流程先从应用层的角度分析流程,用户在launcher上点击图标到Zygote孵化进程,在后续章节叙述。先从Zygote孵化app进程后的ActivityThread.java开始看起。
申明:以下流程是基于AndroidR
1.1ActivityThread.java
在成变量中先创健了一个ApplicaitonThread对象,此处先做一个记号,后面会用到。
final ApplicationThread mAppThread = new ApplicationThread();
此处看到了熟悉的main方法,此处便是应用App启动的入口。在这里创建了ActivityThread对象,调用attach方法。
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
// Install selective syscall interception
AndroidOs.install();
// 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();
// Make sure TrustedCertificateStore looks in the right place for CA certificates
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
// Call per-process mainline module initialization.
initializeMainlineModules();
Process.setArgV0("<pre-initialized>");
//创建主线程的Looper
Looper.prepareMainLooper();
// Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
// It will be in the format "seq=114"
long startSeq = 0;
if (args != null) {
for (int i = args.length - 1; i >= 0; --i) {
if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
startSeq = Long.parseLong(
args[i].substring(PROC_START_SEQ_IDENT.length()));
}
}
}
//创建ActivityThread对象,调用attach
ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
在attach中获取了AMS的代理对象(看framework代码时若遇到IXXXManager的aidl时,大部分情况服务端是XXXManagerService),跨进程调用AMS的attachApplicaiton,并且传入ApplicaitonThread对象。
private void attach(boolean system, long startSeq) {
sCurrentActivityThread = this;
mSystemThread = system;
if (!system) {
android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
UserHandle.myUserId());
RuntimeInit.setApplicationObject(mAppThread.asBinder());
//获取AMS代理对象
final IActivityManager mgr = ActivityManager.getService();
try {
//调用AMS中的attachApplicaiton,并且传入了ApplicaitonThread对象
mgr.attachApplication(mAppThread, startSeq);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
.......
}
}
1.2 ActivityManagerService
跟踪关键信息ApplicationThread,同步调用attachApplicationLocked,注意此处传入了几个重要的进程参数pid、uid。
@Override
public final void attachApplication(IApplicationThread thread, long startSeq) {
if (thread == null) {
throw new SecurityException(