1. 安卓系统启动:
安卓系统在第一个用户进程Init进程启动时,会解析init.rc脚本,启动zygote进程(执行程序为 app _process,代码所在位置时frameworks/base/cmds/app_process/App_main.cpp),然后在zygote中启动system server进程;而在system server进程中,启动各种服务(三种类型);
int main(int argc, char* const argv[])
{
// ...
// runtime
AppRuntime runtime(argv[0], computeArgBlockSize(argc, argv));
// ...
bool startSystemServer = false;
bool application = false;
// ...
if (zygote) {
//
runtime.start("com.android.internal.os.ZygoteInit", args); // 这里是App_main.cpp内部类
} else if (className) {
runtime.start("com.android.internal.os.RuntimeInit", args);
} else {
fprintf(stderr, "Error: no class name or --zygote supplied.\n");
app_usage();
LOG_ALWAYS_FATAL("app_process: no class name or --zygote supplied.");
return 10;
}
}
//App_main.cpp内部类AppRuntime的onZygoteInit(),这个方法先分析下,后面回用到;
virtual void onZygoteInit()
{
// Re-enable tracing now that we're no longer in Zygote.
atrace_set_tracing_enabled(true);
// 调用了binder_open, binder_mmap 两个方法:每个进程fork出来都会调用
sp proc = ProcessState::self();
ALOGV("App process: starting thread pool.\n");
proc->startThreadPool();
}
SystemServer入口:
// SystemServer进程入口
public static void main(String[] args) {
new SystemServer().run();
}
// run()方法
private void run() {
// ...
try {
startBootstrapServices();
startCoreServices();
startOtherServices();
} catch (Throwable ex) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting system services", ex);
throw ex;
}
// ...
}
在引导服务和核心服务(AMS就是核心服务)启动完成后,再启动其他的服务;然后系统启动完成后,会调用AMS.systemReady()方法,也是在这个方法中,启动了我们的launcher进程;
private void startOtherServices() {
// ...
mActivityManagerService.systemReady(new Runnable() {
@Override
public void run() {
Slog.i(TAG, "Making services ready");
mSystemServiceManager.startBootPhase(
SystemService.PHASE_ACTIVITY_MANAGER_READY);
try {
mActivityManagerService.startObservingNativeCrashes();
} catch (Throwable e) {
reportWtf("observing native crashes", e);
}
Slog.i(TAG, "WebViewFactory preparation");
WebViewFactory.prepareWebViewInSystemServer();
try {
startSystemUi(context);
} catch (Throwable e) {
reportWtf("starting System UI", e);
}
try {
if (mountServiceF != null) mountServiceF.systemReady();
} catch (Throwable e) {
reportWtf("making Mount Service ready", e);
}
try {
if (networkScoreF != null) networkScoreF.systemReady();
} catch (Throwable e) {
reportWtf("making Network Score Service ready", e);
}
// ...
}
});
}
AcitivityManagerService.java 中 systemReady() 和 startHomeActivityLocked() 方法:
public void systemReady(final Runnable goingCallback) {
// ..
startHomeActivityLocked(mCurrentUserId);
// ..
}
boolean startHomeActivityLocked(int userId) {
if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL&& mTopAction == null) {
return false;
}
Intent intent = getHomeIntent();
ActivityInfo aInfo =resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
if (aInfo != null) {
intent.setComponent(new ComponentName(
aInfo.applicationInfo.packageName, aInfo.name));
// Don't do this if the home app is currently being
// instrumented.
aInfo = new ActivityInfo(aInfo);
aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
ProcessRecord app = getProcessRecordLocked(aInfo.processName,
aInfo.applicationInfo.uid, true);
if (app == null || app.instrumentationClass == null) {
intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
mStackSupervisor.startHomeActivity(intent, aInfo); // 启动activity:ActivityStackSupervisor中
}
}
return true;
}
接下来的调用十分复杂且代码量很大,我们就只跟踪一下主要的代码;
ActivityStackSupervisor:
void startHomeActivity(Intent intent, ActivityInfo aInfo) {
moveHomeStackTaskToTop(HOME_ACTIVITY_TYPE);
startActivityLocked(null, intent, null, aInfo, null, null, null, null, 0, 0, 0, null,
0, 0, 0, null, false, null, null, null);
}
final int startActivityUncheckedLocked(ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags,
boolean doResume, Bundle options, TaskRecord inTask) {
// ...
targetStack.startActivityLocked(r, newTask, doResume, keepCurTransition, options);
if (!launchTaskBehind) {
// Don't set focus on an activity that's going to the back.
mService.setFocusedActivityLocked(r);
}
return ActivityManager.START_SUCCESS;
}
ActivityStack:
final void startActivityLocked(ActivityRecord r, boolean newTask,
boolean doResume, boolean keepCurTransition, Bundle options) {
// ...
if (doResume) {
mStackSupervisor.resumeTopActivitiesLocked(this, r, options); // 又回到了ActivityStackSupervisor
}
}
ActivityStackSupervisor:
boolean resumeTopActivitiesLocked(ActivityStack targetStack, ActivityRecord target,
Bundle targetOptions) {
if (targetStack == null) {
targetStack = getFocusedStack();
}
// Do targetStack first.
boolean result = false;
if (isFrontStack(targetStack)) {
result = targetStack.resumeTopActivityLocked(target, targetOptions); //再次调用ActivityStack中
}
// ...
return result;
}
ActivityStack:
final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
if (inResumeTopActivity) {
// Don't even start recursing.
return false;
}
boolean result = false;
try {
// Protect against recursion.
inResumeTopActivity = true;
result = resumeTopActivityInnerLocked(prev, options);
} finally {
inResumeTopActivity = false;
}
return result;
}
final boolean resumeTopActivityInnerLocked(ActivityRecord prev, Bundle options) {
// ...
ActivityStack lastStack = mStackSupervisor.getLastStack();
if (next.app != null && next.app.thread != null) {
// ...
} else {
// ...
mStackSupervisor.startSpecificActivityLocked(next, true, true);// 又又回到了ActivityStackSupervisor
}
if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
return true;
}
ActivityStackSupervisor:终于到了启动进程的代码
void startSpecificActivityLocked(ActivityRecord r,
boolean andResume, boolean checkConfig) {
// Is this activity's application already running? 这里就是判断进程是否已经启动
ProcessRecord app = mService.getProcessRecordLocked(r.processName,
r.info.applicationInfo.uid, true); // 根据uid和进程名进行查询
r.task.stack.setLaunchTime(r);
if (app != null && app.thread != null) { // 第一次打开某个进程时,肯定不会进入这个分支
// ... 以后的笔记中再分析
try {
if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
|| !"android".equals(r.info.packageName)) {
app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode,
mService.mProcessStats);
}
realStartActivityLocked(r, app, andResume, checkConfig); // 启动activity
return;
} catch (RemoteException e) {
Slog.w(TAG, "Exception when starting activity "
+ r.intent.getComponent().flattenToShortString(), e);
}
}
// 进程的创建、application的创建和绑定
mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
"activity", r.intent.getComponent(), false, false, true);
}
2. AMS 与 Zygote 的通信过程分析:
mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
"activity", r.intent.getComponent(), false, false, true);
final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName,
boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge,
String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {
long startTime = SystemClock.elapsedRealtime();
ProcessRecord app;
// ...省略一些代码
if (app == null) { // 本节学习进程的创建,所以从此处开始
checkTime(startTime, "startProcess: creating new process record");
// 创建新的Process Record对象
app = newProcessRecordLocked(info, processName, isolated, isolatedUid);
app.crashHandler = crashHandler;
if (app == null) {
return null;
}
mProcessNames.put(processName, app.uid, app);
if (isolated) {
mIsolatedProcesses.put(app.uid, app);
}
checkTime(startTime, "startProcess: done creating new process record");
} else {
// 如果这是进程中新package,则添加到列表
app.addPackage(info.packageName, info.versionCode, mProcessStats);
checkTime(startTime, "startProcess: added package to existing proc");
}
// 当系统未准备完毕,则将当前进程加入到mProcessesOnHold
if (!mProcessesReady
&& !isAllowedWhileBooting(info)
&& !allowWhileBooting) {
if (!mProcessesOnHold.contains(app)) {
mProcessesOnHold.add(app);
}
if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
checkTime(startTime, "startProcess: returning with proc on hold");
return app;
}
checkTime(startTime, "startProcess: stepping in to startProcess");
// 启动进程,注释1;
startProcessLocked(
app, hostingType, hostingNameStr, abiOverride, entryPoint,entryPointArgs);
checkTime(startTime, "startProcess: done starting proc!");
return (app.pid != 0) ? app : null;
}
注释1:startProcessLocked() 方法
private final void startProcessLocked(ProcessRecord app, String hostingType,
String hostingNameStr, String abiOverride, String entryPoint, String[] entryPointArgs) {
long startTime = SystemClock.elapsedRealtime();
// ...
try {
// ...
boolean isActivityProcess = (entryPoint == null);
if (entryPoint == null) entryPoint = "android.app.ActivityThread";
//见2.1
Process.ProcessStartResult startResult = Process.start(entryPoint,
app.processName, uid, uid, gids, debugFlags, mountExternal,
app.info.targetSdkVersion, app.info.seinfo, requiredAbi, instructionSet,
app.info.dataDir, entryPointArgs);
// ...
synchronized (mPidsSelfLocked) {
this.mPidsSelfLocked.put(startResult.pid, app); // 保存pid
// ...
}
} catch (RuntimeException e) {
// ...
}
}
2.1 Process.java中:
// start()方法:
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 abi,
String instructionSet,
String appDataDir,
String[] zygoteArgs) {
try {
return startViaZygote(processClass, niceName, uid, gid, gids,
debugFlags, mountExternal, targetSdkVersion, seInfo,
abi, instructionSet, appDataDir, zygoteArgs);
} catch (ZygoteStartFailedEx ex) {
Log.e(LOG_TAG, "Starting VM process through Zygote failed");
throw new RuntimeException("Starting VM process through Zygote failed", ex);
}
}
// startViaZygote() 方法:
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 abi,
String instructionSet,
String appDataDir,
String[] extraArgs)
throws ZygoteStartFailedEx {
synchronized(Process.class) {
ArrayList argsForZygote = new ArrayList();
// --runtime-init, --setuid=, --setgid=,
// and --setgroups= must go first
argsForZygote.add("--runtime-init");
argsForZygote.add("--setuid=" + uid);
argsForZygote.add("--setgid=" + gid);
// ...
// --setgroups is a comma-separated list
if (gids != null && gids.length > 0) {
StringBuilder sb = new StringBuilder();
sb.append("--setgroups=");
int sz = gids.length;
for (int i = 0; i < sz; i++) {
if (i != 0) {
sb.append(',');
}
sb.append(gids[i]);
}
argsForZygote.add(sb.toString());
}
if (niceName != null) {
argsForZygote.add("--nice-name=" + niceName); // nicieName是class的名字
}
if (seInfo != null) {
argsForZygote.add("--seinfo=" + seInfo);
}
if (instructionSet != null) {
argsForZygote.add("--instruction-set=" + instructionSet);
}
if (appDataDir != null) {
argsForZygote.add("--app-data-dir=" + appDataDir);
}
argsForZygote.add(processClass); // 是刚才传入的 "android.app.ActivityThread"
if (extraArgs != null) {
for (String arg : extraArgs) {
argsForZygote.add(arg);
}
}
// 调用的是zygoteSendArgsAndGetResult() 方法 注释2、注释3
return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote);
}
}
注释2:
private static ZygoteState openZygoteSocketIfNeeded(String abi) throws ZygoteStartFailedEx {
if (primaryZygoteState == null || primaryZygoteState.isClosed()) {
try {
// 这里就是一个名字 "zygote";连接zygote
primaryZygoteState = ZygoteState.connect(ZYGOTE_SOCKET);
} catch (IOException ioe) {
throw new ZygoteStartFailedEx("Error connecting to primary zygote", ioe);
}
}
if (primaryZygoteState.matches(abi)) {
return primaryZygoteState; //返回 以 建立 socket 通讯;
}
// The primary zygote didn't match. Try the secondary.
if (secondaryZygoteState == null || secondaryZygoteState.isClosed()) {
try {
secondaryZygoteState = ZygoteState.connect(SECONDARY_ZYGOTE_SOCKET);
} catch (IOException ioe) {
throw new ZygoteStartFailedEx("Error connecting to secondary zygote", ioe);
}
}
if (secondaryZygoteState.matches(abi)) {
return secondaryZygoteState;
}
throw new ZygoteStartFailedEx("Unsupported zygote ABI: " + abi);
}
注释3:Process.java中zygoteSendArgsAndGetResult();
// zygoteSendArgsAndGetResult() 方法:
private static ProcessStartResult zygoteSendArgsAndGetResult(
ZygoteState zygoteState, ArrayList args)
throws ZygoteStartFailedEx {
try {
final BufferedWriter writer = zygoteState.writer;
final DataInputStream inputStream = zygoteState.inputStream;
writer.write(Integer.toString(args.size())); // 写入参数
writer.newLine();
// 不断向 zygote 写入参数数据
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");
}
writer.write(arg);
writer.newLine();
}
writer.flush();
// 返回赋值
ProcessStartResult result = new ProcessStartResult();
result.pid = inputStream.readInt(); //读pid,是fork出来的进程id
if (result.pid < 0) {
throw new ZygoteStartFailedEx("fork() failed");
}
result.usingWrapper = inputStream.readBoolean();
return result;
} catch (IOException ex) {
zygoteState.close();
throw new ZygoteStartFailedEx(ex);
}
}
3. zygote fork进程的创建过程:
zygote的启动请看这篇:zygote进程启动过程解读
Zygote在main()方法中调用了runSelectLoop(),而 runSelectLoop() 中有一个死循环,当有客户端连接时便会执行ZygoteConnection.runOnce()方法,再经过层层调用后fork出新的应用进程;
boolean runOnce() throws ZygoteInit.MethodAndArgsCaller {
// ...
try {
// ...
// fork子进程,见 3.1
pid = Zygote.forkAndSpecialize(parsedArgs.uid, parsedArgs.gid, parsedArgs.gids,
parsedArgs.debugFlags, rlimits, parsedArgs.mountExternal, parsedArgs.seInfo,
parsedArgs.niceName, fdsToClose, parsedArgs.instructionSet,
parsedArgs.appDataDir);
checkTime(startTime, "zygoteConnection.runOnce: postForkAndSpecialize");
} catch (ZygoteSecurityException ex) {
logAndPrintError(newStderr, "Zygote security policy prevents request: ", ex);
}
try {
if (pid == 0) {
// in child
IoUtils.closeQuietly(serverPipeFd);
serverPipeFd = null;
// fork出来的新进程 见3.2
handleChildProc(parsedArgs, descriptors, childPipeFd, newStderr);
return true;
} else {
// in parent...pid of < 0 means failure
IoUtils.closeQuietly(childPipeFd);
childPipeFd = null;
return handleParentProc(pid, descriptors, serverPipeFd, parsedArgs);
}
} finally { //父进程子进程都会执行
IoUtils.closeQuietly(childPipeFd); // 向AMS 回写pid
IoUtils.closeQuietly(serverPipeFd);
}
}
3.1 Zygote.forkAndSpecialize():
public static int forkAndSpecialize(int uid, int gid, int[] gids, int debugFlags,
int[][] rlimits, int mountExternal, String seInfo, String niceName, int[] fdsToClose,
String instructionSet, String appDataDir) {
long startTime = SystemClock.elapsedRealtime();
VM_HOOKS.preFork();
// jni 方法:framework/base/core/jni/com_android_internal_os_zygote.cpp
int pid = nativeForkAndSpecialize(
uid, gid, gids, debugFlags, rlimits, mountExternal, seInfo, niceName, fdsToClose,
instructionSet, appDataDir);
checkTime(startTime, "Zygote.nativeForkAndSpecialize");
VM_HOOKS.postForkCommon();
checkTime(startTime, "Zygote.postForkCommon");
return pid;
}
进程创建时jni方法调用:
com_android_internal_os_Zygote_nativeForkAndSpecialize() ->
pid_t ForkAndSpecializeCommon() ->
pid_t pid = fork() ->
完成创建;
3.2 子进程的处理:handleChildProc()
private void handleChildProc(Arguments parsedArgs,
FileDescriptor[] descriptors, FileDescriptor pipeFd, PrintStream newStderr)
throws ZygoteInit.MethodAndArgsCaller {
closeSocket(); // 关闭socket连接,fork出来的,有父进程的socket连接,所以也用不到
ZygoteInit.closeServerSocket();
// ...
if (parsedArgs.runtimeInit) {
// 在子进程中启动app的main函数,启动方式有两种:
// 1. 调试模式。在AndroidManifest中设置FLAG_DEBUGGABLE,此时调用脚本启动,
// 执行WrapperInit.execApplication;invokeWith = "/system/bin/logwrapper " +
// app.info.nativeLibraryDir + "/wrap.sh"
if (parsedArgs.invokeWith != null) { // 这个分支进不来
WrapperInit.execApplication(parsedArgs.invokeWith,
parsedArgs.niceName, parsedArgs.targetSdkVersion,
pipeFd, parsedArgs.remainingArgs);
// 2. 正常启动app,默认entryPoint = "android.app.ActivityThread"。
// 因此app启动执行ActivityThread中的main函数
} else {
RuntimeInit.zygoteInit(parsedArgs.targetSdkVersion,
parsedArgs.remainingArgs, null /* classLoader */); //见下方
}
} else {
String className;
try {
className = parsedArgs.remainingArgs[0];
} catch (ArrayIndexOutOfBoundsException ex) {
logAndPrintError(newStderr,
"Missing required class name argument", null);
return;
}
String[] mainArgs = new String[parsedArgs.remainingArgs.length - 1];
System.arraycopy(parsedArgs.remainingArgs, 1,
mainArgs, 0, mainArgs.length);
if (parsedArgs.invokeWith != null) {
WrapperInit.execStandalone(parsedArgs.invokeWith,
parsedArgs.classpath, className, mainArgs);
} else {
ClassLoader cloader;
if (parsedArgs.classpath != null) {
cloader = new PathClassLoader(parsedArgs.classpath,
ClassLoader.getSystemClassLoader());
} else {
cloader = ClassLoader.getSystemClassLoader();
}
try {
ZygoteInit.invokeStaticMain(cloader, className, mainArgs); // 关键代码
} catch (RuntimeException ex) {
logAndPrintError(newStderr, "Error starting.", ex);
}
}
}
}
// RuntimeInit.java中zygoteInit():
public static final void zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader)
throws ZygoteInit.MethodAndArgsCaller {
if (DEBUG) Slog.d(TAG, "RuntimeInit: Starting application from zygote");
redirectLogStreams();
commonInit(); // 一些初始化工作
nativeZygoteInit(); // native方法在 AndroidRuntime.cpp 中
applicationInit(targetSdkVersion, argv, classLoader);
}
// AndroidRuntime.cpp 中:
static void com_android_internal_os_RuntimeInit_nativeZygoteInit(JNIEnv* env, jobject clazz)
{
// 这是一个 virtual 方法,具体实现在app_main.cpp中AndroidRuntime的子类AppRuntime,也就
// 是文章开头分析的onZygoteInit()方法;
gCurRuntime->onZygoteInit();
}
再看看Zygote.invokeStaticMain()方法中的关键代码:
static void invokeStaticMain(ClassLoader loader,
String className, String[] argv)
throws ZygoteInit.MethodAndArgsCaller {
Class cl;
try {
cl = loader.loadClass(className); // 获取class的名字
} catch (ClassNotFoundException ex) {
// ...
}
Method m;
try {
// 这里的方法m 是 android.app.ActivityThread 的 main() 方法
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);
}
// 关键代码
throw new ZygoteInit.MethodAndArgsCaller(m, argv);
}
ZygoteInit内部类:
/**
* Helper exception class which holds a method and arguments and
* can call them. This is used as part of a trampoline to get rid of
* the initial process setup stack frames.
*/
public static class MethodAndArgsCaller extends Exception
implements Runnable {
/** method to call */
private final Method mMethod;
/** argument array */
private final String[] mArgs;
public MethodAndArgsCaller(Method method, String[] args) {
mMethod = method;
mArgs = args;
}
public void run() {
// 这里的方法 mMethod 是 android.app.ActivityThread 的 main() 方法
try {
// 进程真正开始启动 看 ActivityThread的main方法
mMethod.invoke(null, new Object[] { mArgs });
} catch (IllegalAccessException ex) {
throw new RuntimeException(ex);
} catch (InvocationTargetException ex) {
Throwable cause = ex.getCause();
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
} else if (cause instanceof Error) {
throw (Error) cause;
}
throw new RuntimeException(ex);
}
}
}
备注1. ActivityThread.java 的分析:
备注1.1 main()方法:
public static void main(String[] args) {
// ... 省略部分代码
//(1)准备MainLooper
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false); //(2)这里是重点
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
// ...
//(3)消息机制:有兴趣可以看看之前的文章中有handler消息机制的分析;
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
备注1.2 attach()方法:
private void attach(boolean system) {
sCurrentActivityThread = this;
mSystemThread = system;
if (!system) { // 非系统app
ViewRootImpl.addFirstDrawHandler(new Runnable() {
@Override
public void run() {
ensureJitEnabled();
}
});
android.ddm.DdmHandleAppName.setAppName("",
UserHandle.myUserId());
RuntimeInit.setApplicationObject(mAppThread.asBinder());
final IActivityManager mgr = ActivityManagerNative.getDefault(); // 获取到AMS
try {
// binder通讯,和之前的一样;mAppThread -> ApplicationThread,底层是BBinder
mgr.attachApplication(mAppThread); // 注释4
} catch (RemoteException ex) {
// Ignore
}
// Watch for getting close to heap limit.
BinderInternal.addGcWatcher(new Runnable() {
@Override public void run() {
if (!mSomeActivitiesChanged) {
return;
}
Runtime runtime = Runtime.getRuntime();
long dalvikMax = runtime.maxMemory();
long dalvikUsed = runtime.totalMemory() - runtime.freeMemory();
if (dalvikUsed > ((3*dalvikMax)/4)) {
mSomeActivitiesChanged = false;
try {
mgr.releaseSomeActivities(mAppThread);
} catch (RemoteException e) {
}
}
}
});
} else {
// ...
}
}
注释4:ActivityManagerService.java 中 attachApplication()
// attachApplication()
public final void attachApplication(IApplicationThread thread) {
synchronized (this) {
int callingPid = Binder.getCallingPid(); // 从Binder驱动中获取pid
final long origId = Binder.clearCallingIdentity();
attachApplicationLocked(thread, callingPid); // 如下attachApplicationLocked()
Binder.restoreCallingIdentity(origId);
}
// ...
if (normalMode) {
try {
if (mStackSupervisor.attachApplicationLocked(app)) { //启动activity,下一节的内容
didSomething = true;
}
} catch (Exception e) {
Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
badApp = true;
}
}
}
//attachApplicationLocked()
private final boolean attachApplicationLocked(IApplicationThread thread, int pid) {
ProcessRecord app;
// ...
if (app.thread != null) { // 创建进程,第一次进来,此时肯定为空
handleAppDiedLocked(app, true, true);
}
// ...
app.makeActive(thread, mProcessStats); // 将ProcessRecord(app)和thread绑定
// ...
// 主要是这个方法,回调到 AppThread 的 bindApplication() 方法;
thread.bindApplication(processName, appInfo, providers, app.instrumentationClass,
profilerInfo, app.instrumentationArguments, app.instrumentationWatcher,
app.instrumentationUiAutomationConnection, testMode, enableOpenGlTrace,
isRestrictedBackupMode || !normalMode, app.persistent,
new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
mCoreSettingsObserver.getCoreSettingsLocked());
// ...
}
- application 的创建和绑定过程:
ActivityThread的内部类ApplicationThread
// ApplicationThread中的bindApplication()方法:
public final void bindApplication( //... 一大推参数 ) {
// ...
sendMessage(H.BIND_APPLICATION, data);
}
// ActivityThread 中 消息处理类 H:
private class H extends Handler {
// ...
public void handleMessage(Message msg) {
switch (msg.what) {
// ...
case BIND_APPLICATION:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
AppBindData data = (AppBindData)msg.obj;
handleBindApplication(data);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
// ...
}
// ActivityThread 中
private void handleBindApplication(AppBindData data) {
// ...
// 创建一个LoadApk对象(包含apk的所有信息,例如资源、包名、类等等)
data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
== 0) {
mDensityCompatMode = true;
Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
}
updateDefaultDensity();
// 创建context
final ContextImpl appContext = ContextImpl.createAppContext(this, data.info);
// ...
try { // 创建绑定application
Application app = data.info.makeApplication(data.restrictedBackupMode, null); // 注释5
mInitialApplication = app;
try { // 调用application的onCreate()方法:
mInstrumentation.callApplicationOnCreate(app);
} catch (Exception e) {
if (!mInstrumentation.onException(app, e)) {
throw new RuntimeException(
"Unable to create application " + app.getClass().getName() + ": " + e.toString(), e);
}
}
} finally {
StrictMode.setThreadPolicy(savedPolicy);
}
}
注释5:
public Application makeApplication(boolean forceDefaultAppClass,
Instrumentation instrumentation) {
if (mApplication != null) {
return mApplication;
}
Application app = null;
// appClass 是 PMS 启动时或者安装时解析AndroidManifest.xml配置中配置Application的class
String appClass = mApplicationInfo.className;
if (forceDefaultAppClass || (appClass == null)) { // 没有配置就使用系统的Application
appClass = "android.app.Application";
}
try {
java.lang.ClassLoader cl = getClassLoader();
if (!mPackageName.equals("android")) {
initializeJavaContextClassLoader();
}
ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
app = mActivityThread.mInstrumentation.newApplication(
cl, appClass, appContext);
appContext.setOuterContext(app);
} catch (Exception e) {
if (!mActivityThread.mInstrumentation.onException(app, e)) {
throw new RuntimeException(
"Unable to instantiate application " + appClass
+ ": " + e.toString(), e);
}
}
mActivityThread.mAllApplications.add(app);
mApplication = app;
if (instrumentation != null) {
try {
instrumentation.callApplicationOnCreate(app);
} catch (Exception e) {
if (!instrumentation.onException(app, e)) {
throw new RuntimeException(
"Unable to create application " + app.getClass().getName()
+ ": " + e.toString(), e);
}
}
}
// ...
return app;
}
进程创建过程:
- AMS判断进程是否创建;
- AMS向Zygote发送进程创建的命令(socket);
- Zygote接收到AMS创建进程的命令后,fork出进程;
- 进程创建完成后,启动binder驱动,然后调用ActivityThread.main()方法;
- ActivityThread的main()方法中向AMS发送绑定IApplicationThread的Binder对象;
- AMS通过调用ApplicationThread,创建和绑定Application;
- 最后AMS真正启动Activity;