概述
Android中启动某个Activity,将先启动Activity所在的应用。应用启动时会启动一个以应用包名为进程名的进程,该进程有一个主线程,叫ActivityThread,也叫做UI线程。
本系列博客将详细阐述Activity的启动流程。
Activity启动时的概要交互流程
用户从Launcher程序点击应用图标可启动应用的入口Activity,Activity启动时需要多个进程之间的交互,Android系统中有一个zygote进程专用于孵化Android框架层和应用层程序的进程。还有一个system_server进程,该进程里运行了很多binder service,例如ActivityManagerService,PackageManagerService,WindowManagerService,这些binder service分别运行在不同的线程中,其中ActivityManagerService负责管理Activity栈,应用进程,task。
Activity启动时的概要交互流程如下图如下所示
用户在Launcher程序里点击应用图标时,会通知ActivityManagerService启动应用的入口Activity,ActivityManagerService发现这个应用还未启动,则会通知Zygote进程孵化出应用进程,然后在这个dalvik应用进程里执行ActivityThread的main方法。应用进程接下来通知ActivityManagerService应用进程已启动,ActivityManagerService保存应用进程的一个代理对象,这样ActivityManagerService可以通过这个代理对象控制应用进程,然后ActivityManagerService通知应用进程创建入口Activity的实例,并执行它的生命周期方法。
Activity启动相关类的类图
在介绍Activity的详细启动流程之前,先为大家介绍Activity启动时涉及到的类,这样大家可以有大概的了解,不至于在细节中迷失。
Activity启动时涉及到的类有
- IActivityManager相关类
- IApplicationThread相关类
- ActivityManagerService相关类
IActivityManager相关类
Activity的管理采用binder机制,管理Activity的接口是IActivityManager。
ActivityManagerService实现了Activity管理功能,位于system_server进程,ActivityManagerProxy对象是ActivityManagerService在普通应用进程的一个代理对象,应用进程通过ActivityManagerProxy对象调用ActivityManagerService提供的功能。
应用进程并不会直接创建ActivityManagerProxy对象,而是通过调用ActiviyManagerNative类的工具方法getDefault方法得到ActivityManagerProxy对象。所以在应用进程里通常这样启动Activty:
ActivityManagerNative.getDefault().startActivity()
IApplicationThread相关类
应用进程需要调用ActivityManagerService提供的功能,而ActivityManagerService也需要主动调用应用进程以控制应用进程并完成指定操作。这样ActivityManagerService也需要应用进程的一个Binder代理对象,而这个代理对象就是ApplicationThreadProxy对象。
ActivityManagerService通过IApplicationThread接口管理应用进程,ApplicationThread类实现了IApplicationThread接口,实现了管理应用的操作,ApplicationThread对象运行在应用进程里。ApplicationThreadProxy对象是ApplicationThread对象在ActivityManagerService线程 (ActivityManagerService线程运行在system_server进程)内的代理对象,ActivityManagerService通过ApplicationThreadProxy对象调用ApplicationThread提供的功能,比如让应用进程启动某个Activity。
ActivityManagerService相关类
ActivityManagerService管理Activity时,主要涉及以下几个类:
- 1 ActivityManagerService,它是管理activity的入口类,聚合了ProcessRecord对象和ActivityStack对象
- 2 ProcessRecord,表示应用进程记录,每个应用进程都有对应的ProcessRecord对象
- 3 ActivityStack,该类主要管理回退栈
- 4 ActivityRecord,每次启动一个Actvity会有一个对应的ActivityRecord对象,表示Activity的一个记录
- 5 ActivityInfo,Activity的信息,比如启动模式,taskAffinity,flag信息(这些信息在AndroidManifest.xml里声明Activity时填写)
- 6 TaskRecord,Task记录信息,一个Task可能有多个ActivityRecord,但是一个ActivityRecord只能属于一个TaskRecord
注意:
ActivityManagerService里只有一个ActivityStack对象,并不会像Android官方文档描述的一样,每个Task都有一个activity stack对象。ActivityStack管理ActivityRecord时,不是下面这样组织ActivityRecord的:
List<TaskRecord> taskList; //ActivityStack类
List<ActivityRecord> recordList;// TaskRecord类
而是像下面这样组织ActivityRecord:
ArrayList<ActivityRecord> mHistory = new ArrayList<ActivityRecord>(); //ActivityStack类里
TaskRecord task; // ActivityRecord类里
也就是说ActivityManagerService组织回退栈时以ActivityRecord为基本单位,所有的ActivityRecord放在同一个ArrayList里,可以将mHistory看作一个栈对象,索引0所指的对象位于栈底,索引mHistory.size()-1所指的对象位于栈顶。
但是ActivityManagerService调度ActivityRecord时以task为基本单位,每个ActivityRecord对象都属于某个TaskRecord,一个TaskRecord可能有多个ActivityRecord。
ActivityStack没有TaskRecord列表的入口,只有在ActivityManagerService才有TaskRecord列表的入口:
final ArrayList<TaskRecord> mRecentTasks
ActivityStack管理ActivityRecord时,将属于同一个task的ActivityRecord放在一起,如下所示:
回退栈里可看到两个task,假设上面的task为task1,下面的task为task2,task1包含D,E两个Activity Record,task2包含3个ActivityRecord。task1位于回退栈的栈顶,task2位于task1下面,task1中E位于栈顶,task2中C位于栈顶。需注意两个task的Activity不会混在一起,也就是说task2的B不能放在task1的D和E中间。
因为回退栈是栈结构,所以此时不断按返回键,显示的Activity的顺序为E–>D–>C–>B–>A。
Activity启动的详细流程
1. Activity调用ActivityManagerService启动应用
2. ActivityManagerService调用Zygote孵化应用进程
3. Zygote孵化应用进程
4. 新进程启动ActivityThread
5. 应用进程绑定到ActivityManagerService
6. ActivityThread的Handler处理启动Activity的消息
1. Activity调用ActivityManagerService启动应用
在launcher应用程序里启动应用时,点击应用图标后,launcher程序会调用startActivity启动应用,传递的intent参数:
intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setComponent(className);
activity最终调用Instrumentation的execStartActivity来启动应用:
//Activity类
public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
if (mParent == null) {
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);
if (ar != null) {
mMainThread.sendActivityResult(
mToken, mEmbeddedID, requestCode, ar.getResultCode(),
ar.getResultData());
}
//...
}else{
//...
}
Instrumentation调用ActivityManagerProxy对象的startActivity方法启动Activity,而ActivityManagerProxy只是ActivityManagerService对象在应用进程的一个代理对象,ActivityManagerProxy最终调用ActivityManagerService的startActvity方法启动Activity。
//Instrumentation类
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
//...
try{
//...
int result = ActivityManagerNative.getDefault()
.startActivity(whoThread, intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target != null ? target.mEmbeddedID : null,
requestCode, 0, null, null, options);
} catch (RemoteException e) {
}
//...
}
2. ActivityManagerService调用Zygote孵化应用进程
ActivityManagerProxy对象调用ActivityManagerService对象(运行在system_server进程)的startActivity方法以启动应用,startActivity方法接下来调用startActivityAsUser方法以启动应用。在startActivityAsUser方法里会调用ActivityStack的startActivityMayWait方法以启动应用,startActivityMayWait方法里启动应用时,需先根据intent在系统中找到合适的应用的activity,如果有多个activity可选择,则会弹出ResolverActivity让用户选择合适的应用。
//ActivityStack类
final int startActivityMayWait(IApplicationThread caller, int callingUid,
Intent intent, String resolvedType, IBinder resultTo,
String resultWho, int requestCode, int startFlags, String profileFile,
ParcelFileDescriptor profileFd, WaitResult outResult, Configuration config,
Bundle options, int userId) {
//…
//根据intent在系统中找到合适的应用的activity,如果有多个activity可选择,
//则会弹出ResolverActivity让用户选择合适的应用。
ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags,
profileFile, profileFd, userId);
//…
int res = startActivityLocked(caller, intent, resolvedType,
aInfo, resultTo, resultWho, requestCode, callingPid, callingUid,
startFlags, options, componentSpecified, null);
//…
}
在startActivityLocked方法里,对传过来的参数做一些校验,然后创建ActivityRecord对象,再调用startActivityUncheckedLocked方法启动Activity。
startActivityUncheckedLocked方法负责调度ActivityRecord和Task,理解该方法是理解Actvity启动模式的关键。
startActivityUncheckedLocked方法调度task的算法非常复杂,和当前回退栈,要启动的acitivity的启动模式以及taskAffinity属性,启动activity时设置的intent的flag等诸多要素相关,intent的flag就有很多种情况,故此算法非常复杂,需要阅读源码并结合特定启动情况才能理解。
后续会介绍startActivityUncheckedLocked方法的实现,并结合特定场景分析调度算法。
接下来调用startActivityLocked将ActivityRecord加入到回退栈里:
//ActivityStack类
final int startActivityUncheckedLocked(ActivityRecord r,
ActivityRecord sourceRecord, int startFlags, boolean doResume,
Bundle options) {
//...
startActivityLocked(r, newTask, doResume, keepCurTransition, options);
//...
}
在startActivityLocked里调用resumeTopActivityLocked显示栈顶Activity:
//ActivityStack类
private final void startActivityLocked(ActivityRecord r, boolean newTask,
boolean doResume, boolean keepCurTransition, Bundle options) {
//...
if (doResume) {
resumeTopActivityLocked(null);
}
}
resumeTopActivityLocked(null)会调用另一个resumeTopActivityLocked方法显示栈顶的acitivity:
//ActivityStack类
final boolean resumeTopActivityLocked(ActivityRecord prev) {
return resumeTopActivityLocked(prev, null);
}
因为应用还未启动过,所以调用startSpecificActivityLocked启动应用,执行逻辑如下:
//ActivityStack类
final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
//...
if (next.app != null && next.app.thread != null) {
//…
}else{
//…
startSpecificActivityLocked(next, true, true);
}
//...
}
在startSpecificActivityLocked里调用mService.startProcessLocked启动应用:
//ActivityStack类
private final void startSpecificActivityLocked(ActivityRecord r,
boolean andResume, boolean checkConfig) {
ProcessRecord app = mService.getProcessRecordLocked(r.processName,
r.info.applicationInfo.uid);
//...
mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
"activity", r.intent.getComponent(), false, false);
}
在ActivityManagerService的startProcessLocked方法里:
//ActivityManagerService类
final ProcessRecord startProcessLocked(String processName,
ApplicationInfo info, boolean knownToBeDead, int intentFlags,
String hostingType, ComponentName hostingName, boolean allowWhileBooting,
boolean isolated) {
ProcessRecord app;
if (!isolated) {
app = getProcessRecordLocked(processName, info.uid);
} else {
//...
}
//...
if (app == null) {
app = newProcessRecordLocked(null, info, processName, isolated);
if (app == null) {
Slog.w(TAG, "Failed making new process record for "
+ processName + "/" + info.uid + " isolated=" + isolated);
return null;
}
mProcessNames.put(processName, app.uid, app);
if (isolated) {
mIsolatedProcesses.put(app.uid, app);
}
} else {
//..
}
//...
startProcessLocked(app, hostingType, hostingNameStr);
//...
}
在startProcessLocked方法里:
//ActivityManagerService类
private final void startProcessLocked(ProcessRecord app,
String hostingType, String hostingNameStr) {
//...
try {
//...
// Start the process. It will either succeed and return a result containing
// the PID of the new process, or else throw a RuntimeException.
//Zygote孵化dalvik应用进程后,会执行android.app.ActivityThread类的main方法
Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
app.processName, uid, uid, gids, debugFlags, mountExternal,
app.info.targetSdkVersion, app.info.seinfo, null);
//...
} catch (RuntimeException e) {
//...
}
}
在Process类的start方法里:
/Process类
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) {
try{
startViaZygote(processClass, niceName, uid, gid, gids,
debugFlags, mountExternal, targetSdkVersion, seInfo, zygoteArgs);
}catch (ZygoteStartFailedEx ex) {
//...
}
}
在Process类的startViaZygote方法里,会计算启动应用进程用的各个参数,然后再调用zygoteSendArgsAndGetResult方法将这些参数通过socket发送给zygote进程,zygote进程会孵化出新的dalvik应用进程,然后告诉ActivityManagerService新启动的进程的pid。
3. Zygote孵化应用进程
zygote进程将ZygoteInit作为启动类,会执行它的main方法,先注册ZygoteSocket,然后调用runSelectLoop方法,runSelectLoop方法会调用方法在ZygoteSocket上监听请求,如果别的进程通过ZygoteSocket请求孵化进程,则孵化进程。
runSelectLoop方法的主要代码:
//ZygoteInit类
private static void runSelectLoopMode() throws MethodAndArgsCaller {
//...
while (true) {
//...
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 {
//若客户发送孵化进程的请求过来,
//此时便需要调用ZygoteConnection的runOnce方法孵化进程
boolean done;
done = peers.get(index).runOnce();
if (done) {
peers.remove(index);
fds.remove(index);
}
}
}
}
在runOnce方法里调用Zygote.forkAndSpecialize方法孵化进程,如果返回值为0表示是在孵化出来的应用进程里,此时会调用handleChildProc进行一些处理,并使用异常机制进行逃逸,会直接逃逸至ZygoteInit的main方法。
//ZygoteConnection类
boolean runOnce() throws ZygoteInit.MethodAndArgsCaller {
//...
try {
//...
pid = Zygote.forkAndSpecialize(parsedArgs.uid, parsedArgs.gid, parsedArgs.gids,
parsedArgs.debugFlags, rlimits, parsedArgs.mountExternal, parsedArgs.seInfo,
parsedArgs.niceName);
}
//...
try {
if (pid == 0) {
// in child
IoUtils.closeQuietly(serverPipeFd);
serverPipeFd = null;
//handleChildProc是一个很重要的函数,在该函数里使用了异常进行逃逸
handleChildProc(parsedArgs, descriptors, childPipeFd, newStderr);
//...
} else {
//...
}
} finally {
//...
}
}
3.1 Zygote.forkAndSpecialize
Zygote的forkAndSpecialize方法会调用nativeForkAndSpecialize方法孵化进程,nativeForkAndSpecialize是一个本地方法,它的实现在dalvik/vm/native/dalvik_system_Zygote.cpp里,在该cpp文件里与nativeForkAndSpecialize对应的C++方法是Dalvik_dalvik_system_Zygote_forkAndSpecialize,在该方法里会调用forkAndSpecializeCommon孵化进程,在forkAndSpecializeCommon方法里会调用fork系统调用创建进程,因为使用的是fork机制所以创建进程的效率比较高。
3.2 handleChildProc
handleChildProc方法主要代码:
//ZygoteConnection类
private void handleChildProc(Arguments parsedArgs,
FileDescriptor[] descriptors, FileDescriptor pipeFd, PrintStream newStderr)
throws ZygoteInit.MethodAndArgsCaller {
//...
if (parsedArgs.runtimeInit) {
//...
} else {
String className;
try {
//这里得到的classname实际是android.app.ActivityThread
className = parsedArgs.remainingArgs[0];
} catch (ArrayIndexOutOfBoundsException ex) {
logAndPrintError(newStderr,
"Missing required class name argument", null);
return;
}
//...
if (parsedArgs.invokeWith != null) {
//...
} else {
ClassLoader cloader;
if (parsedArgs.classpath != null) {
cloader = new PathClassLoader(parsedArgs.classpath,
ClassLoader.getSystemClassLoader());
} else {
cloader = ClassLoader.getSystemClassLoader();
}
//调用ZygoteInit.invokeStaticMain执行android.app.ActivityThread的main方法
try {
ZygoteInit.invokeStaticMain(cloader, className, mainArgs);
} catch (RuntimeException ex) {
logAndPrintError(newStderr, "Error starting.", ex);
}
}
}
}
ZygoteInit的invokeStaticMain方法并不会直接执行className的main方法,而是会构造一个 ZygoteInit.MethodAndArgsCaller异常,然后抛出来,通过异常机制会直接跳转到ZygoteInit的main方法, ZygoteInit.MethodAndArgsCaller类实现了Runnable方法,在run方法里会执行要求执行的main方法,故此跳转到ZygoteInit的main方法后,异常会被捕获,然后执行方法caller.run(),这样便会执行android.app.ActivityThread的main方法。
ZygoteInit的invokeStaticMain方法主要代码:
//ZygoteInit类
static void invokeStaticMain(ClassLoader loader,
String className, String[] argv)
throws ZygoteInit.MethodAndArgsCaller {
//...
Method m;
try {
m = cl.getMethod("main", new Class[] { String[].class });
} catch(//...){
}
//...
throw new ZygoteInit.MethodAndArgsCaller(m, argv);
}
ZygoteInit.MethodAndArgsCaller主要代码:
public static class MethodAndArgsCaller extends Exception
implements Runnable {
//...
public void run() {
try {
mMethod.invoke(null, new Object[] { mArgs });
}//...
}
}
ZygoteInit的main方法相关代码:
//ZygoteInit类
public static void main(String argv[]) {
try {
//...
} catch (MethodAndArgsCaller caller) {
caller.run();
} catch (RuntimeException ex) {
//...
}
}
4. 新进程启动ActivityThread
Zygote进程孵化出新的应用进程后,会执行ActivityThread类的main方法。在该方法里会先准备好Looper和消息队列,然后调用attach方法将应用进程绑定到ActivityManagerService,然后进入loop循环,不断地读取消息队列里的消息,并分发消息。
//ActivityThread类
public static void main(String[] args) {
//...
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
AsyncTask.init();
//...
Looper.loop();
//...
}
5. 应用进程绑定到ActivityManagerService
在ActivityThread的main方法里调用thread.attach(false);attach方法的主要代码如下所示:
//ActivityThread类
private void attach(boolean system) {
sThreadLocal.set(this);
mSystemThread = system;
if (!system) {
//...
IActivityManager mgr = ActivityManagerNative.getDefault();
try {
//调用ActivityManagerService的attachApplication方法
//将ApplicationThread对象绑定至ActivityManagerService,
//这样ActivityManagerService就可以
//通过ApplicationThread代理对象控制应用进程
mgr.attachApplication(mAppThread);
} catch (RemoteException ex) {
// Ignore
}
} else {
//...
}
//...
}
ActivityManagerService的attachApplication方法执行attachApplicationLocked(thread, callingPid)进行绑定。
//ActivityManagerService类
private final boolean attachApplicationLocked(IApplicationThread thread,
int pid) {
ProcessRecord app;
//...
app.thread = thread;
//...
try {
//...
thread.bindApplication(processName, appInfo, providers,
app.instrumentationClass, profileFile, profileFd, profileAutoStop,
app.instrumentationArguments, app.instrumentationWatcher, testMode,
enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
mCoreSettingsObserver.getCoreSettingsLocked());
//...
} catch (Exception e) {
//...
}
//...
ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
if (hr != null && normalMode) {
if (hr.app == null && app.uid == hr.info.applicationInfo.uid
&& processName.equals(hr.processName)) {
try {
if (mHeadless) {
Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
} else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
//mMainStack.realStartActivityLocked真正启动activity
didSomething = true;
}
} catch (Exception e) {
//...
}
} else {
//...
}
}
//...
return true;
}
attachApplicationLocked方法有两个重要的函数调用thread.bindApplication和mMainStack.realStartActivityLocked。thread.bindApplication将应用进程的ApplicationThread对象绑定到ActivityManagerService,也就是说获得ApplicationThread对象的代理对象。mMainStack.realStartActivityLocked通知应用进程启动Activity。
5.1 thread.bindApplication
thread对象其实是ActivityThread里ApplicationThread对象在ActivityManagerService的代理对象,故此执行thread.bindApplication,最终会调用ApplicationThread的bindApplication方法,该方法的主要代码如下所示:
//ActivityThread类
public final void bindApplication(String processName,
ApplicationInfo appInfo, List<ProviderInfo> providers,
ComponentName instrumentationName, String profileFile,
ParcelFileDescriptor profileFd, boolean autoStopProfiler,
Bundle instrumentationArgs, IInstrumentationWatcher instrumentationWatcher,
int debugMode, boolean enableOpenGlTrace, boolean isRestrictedBackupMode,
boolean persistent, Configuration config, CompatibilityInfo compatInfo,
Map<String, IBinder> services, Bundle coreSettings) {
//...
AppBindData data = new AppBindData();
data.processName = processName;
data.appInfo = appInfo;
data.providers = providers;
data.instrumentationName = instrumentationName;
data.instrumentationArgs = instrumentationArgs;
data.instrumentationWatcher = instrumentationWatcher;
data.debugMode = debugMode;
data.enableOpenGlTrace = enableOpenGlTrace;
data.restrictedBackupMode = isRestrictedBackupMode;
data.persistent = persistent;
data.config = config;
data.compatInfo = compatInfo;
data.initProfileFile = profileFile;
data.initProfileFd = profileFd;
data.initAutoStopProfiler = false;
queueOrSendMessage(H.BIND_APPLICATION, data);
}
这样调用queueOrSendMessage会往ActivityThread的消息队列发送消息,消息的用途是BIND_APPLICATION。
这样会在handler里处理BIND_APPLICATION消息,接着调用handleBindApplication方法处理绑定消息。
//ActivityThread类
private void handleBindApplication(AppBindData data) {
//...
ApplicationInfo instrApp = new ApplicationInfo();
instrApp.packageName = ii.packageName;
instrApp.sourceDir = ii.sourceDir;
instrApp.publicSourceDir = ii.publicSourceDir;
instrApp.dataDir = ii.dataDir;
instrApp.nativeLibraryDir = ii.nativeLibraryDir;
LoadedApk pi = getPackageInfo(instrApp, data.compatInfo,
appContext.getClassLoader(), false, true);
ContextImpl instrContext = new ContextImpl();
instrContext.init(pi, null, this);
//...
if (data.instrumentationName != null) {
//...
} else {
//注意Activity的所有生命周期方法都会被Instrumentation对象所监控,
//也就说执行Activity的生命周期方法前后一定会调用Instrumentation对象的相关方法
//并不是说只有跑单测用例才会建立Instrumentation对象,
//即使不跑单测也会建立Instrumentation对象
mInstrumentation = new Instrumentation();
}
//...
try {
//...
Application app = data.info.makeApplication(data.restrictedBackupMode, null);
mInitialApplication = app;
//...
try {
mInstrumentation.onCreate(data.instrumentationArgs);
}catch (Exception e) {
//...
}
try {
//这里会调用Application的onCreate方法
//故此Applcation对象的onCreate方法会比ActivityThread的main方法后调用
//但是会比这个应用的所有activity先调用
mInstrumentation.callApplicationOnCreate(app);
} catch (Exception e) {
//...
}
} finally {
StrictMode.setThreadPolicy(savedPolicy);
}
}
5.2 mMainStack.realStartActivityLocked
realStartActivity会调用scheduleLaunchActivity启动activity,主要代码:
//ActivityStack类
final boolean realStartActivityLocked(ActivityRecord r,
ProcessRecord app, boolean andResume, boolean checkConfig)
throws RemoteException {
//...
try {
//...
app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
System.identityHashCode(r), r.info,
new Configuration(mService.mConfiguration),
r.compat, r.icicle, results, newIntents, !andResume,
mService.isNextTransitionForward(), profileFile, profileFd,
profileAutoStop);
//...
} catch (RemoteException e) {
//...
}
//...
return true;
}
同样app.thread也只是ApplicationThread对象在ActivityManagerService的一个代理对象而已,最终会调用ApplicationThread的scheduleLaunchActivity方法。
//ActivityThread类
public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
ActivityInfo info, Configuration curConfig, CompatibilityInfo compatInfo,
Bundle state, List<ResultInfo> pendingResults,
List<Intent> pendingNewIntents, boolean notResumed, boolean isForward,
String profileName, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
ActivityClientRecord r = new ActivityClientRecord();
r.token = token;
r.ident = ident;
r.intent = intent;
r.activityInfo = info;
r.compatInfo = compatInfo;
r.state = state;
r.pendingResults = pendingResults;
r.pendingIntents = pendingNewIntents;
r.startsNotResumed = notResumed;
r.isForward = isForward;
r.profileFile = profileName;
r.profileFd = profileFd;
r.autoStopProfiler = autoStopProfiler;
updatePendingConfiguration(curConfig);
queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
}
这里调用了queueOrSendMessage往ActivityThread的消息队列发送了消息,消息的用途是启动Activity,接下来ActivityThread的handler便会处理该消息。
6. ActivityThread的Handler处理启动Activity的消息
ActivityThread的handler调用handleLaunchActivity处理启动Activity的消息,handleLaunchActivity的主要代码如下所示:
//ActivityThread类
private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
//...
Activity a = performLaunchActivity(r, customIntent);
if (a != null) {
//...
handleResumeActivity(r.token, false, r.isForward,
!r.activity.mFinished && !r.startsNotResumed);
//...
} else {
//...
}
}
handleLaunchActivity方法里有有两个重要的函数调用,performLaunchActivity和handleResumeActivity,performLaunchActivity会调用Activity的onCreate,onStart,onResotreInstanceState方法,handleResumeActivity会调用Activity的onResume方法.
6.1 performLaunchActivity
performLaunchActivity的主要代码如下所示:
//ActivityThread类
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
//...
Activity activity = null;
try {
java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
//...
} catch (Exception e) {
//...
}
try {
//r.packageInfo.makeApplication实际并未创建Application对象,
//因为bindApplication过程已经创建了Application对象,
//makeApplication方法会返回已创建的Application对象
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
//...
if (activity != null) {
//...
//将application对象,appContext对象绑定到新建的activity对象
activity.attach(appContext, this, getInstrumentation(), r.token,
r.ident, app, r.intent, r.activityInfo, title, r.parent,
r.embeddedID, r.lastNonConfigurationInstances, config);
//...
//会调用Activity的onCreate方法
mInstrumentation.callActivityOnCreate(activity, r.state);
//...
//...
//调用Activity的onStart方法
if (!r.activity.mFinished) {
activity.performStart();
r.stopped = false;
}
if (!r.activity.mFinished) {
if (r.state != null) {
//会调用Activity的onRestoreInstanceState方法
mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
}
}
if (!r.activity.mFinished) {
activity.mCalled = false;
mInstrumentation.callActivityOnPostCreate(activity, r.state);
//...
}
}
//...
} catch (SuperNotCalledException e) {
throw e;
} catch (Exception e) {
//...
}
return activity;
}
6.2 handleResumeActivity
handleResumeActivity的主要代码如下所示:
//ActivityThread类
final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward,
boolean reallyResume) {
//...
//performResumeActivity最终会调用Activity的onResume方法
ActivityClientRecord r = performResumeActivity(token, clearHide);
if (r != null) {
final Activity a = r.activity;
//...
//显示界面
if (r.window == null && !a.mFinished && willBeVisible) {
r.window = r.activity.getWindow();
View decor = r.window.getDecorView();
decor.setVisibility(View.INVISIBLE);
ViewManager wm = a.getWindowManager();
WindowManager.LayoutParams l = r.window.getAttributes();
a.mDecor = decor;
l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
l.softInputMode |= forwardBit;
if (a.mVisibleFromClient) {
a.mWindowAdded = true;
wm.addView(decor, l);
}
//...
} else if (!willBeVisible) {
//...
}
// Tell the activity manager we have resumed.
if (reallyResume) {
try {
ActivityManagerNative.getDefault().activityResumed(token);
} catch (RemoteException ex) {
}
}
} else {
//...
}
}
performResumeActivity的主要代码如下所示:
//ActivityThread类
public final ActivityClientRecord performResumeActivity(IBinder token,
boolean clearHide) {
ActivityClientRecord r = mActivities.get(token);
//...
if (r != null && !r.activity.mFinished) {
//...
try {
//...
//会调用Activity的onResume方法
r.activity.performResume();
//...
} catch (Exception e) {
//...
}
}
return r;
}
总结Activity的概要启动流程:
用户在Launcher程序里点击应用图标时,会通知ActivityManagerService启动应用的入口Activity,ActivityManagerService发现这个应用还未启动,则会通知Zygote进程孵化出应用进程,然后在这个dalvik应用进程里执行ActivityThread的main方法。应用进程接下来通知ActivityManagerService应用进程已启动,ActivityManagerService保存应用进程的一个代理对象,这样ActivityManagerService可以通过这个代理对象控制应用进程,然后ActivityManagerService通知应用进程创建入口Activity的实例,并执行它的生命周期方法
现在也可以理解:
如果应用的组件(包括所有组件Activity,Service,ContentProvider,Receiver) 被启动,肯定会先启动以应用包名为进程名的进程,这些组件都会运行在应用包名为进程名的进程里,并且是在主线程里。应用进程启动时会先创建Application对象,并执行Application对象的生命周期方法,然后才启动应用的组件。
有一种情况比较特殊,那就是为组件设置了特殊的进程名,也就是说通过android:process设置进程名的情况,此时组件运行在单独的进程内。