在Android桌面Launcher源码浅析中介绍了Android的桌面程序Launcher是如何响应用户点击事件并启动App的,这篇文章继续介绍App在Android系统层的启动流程。
Launcher
最终通过frameworks/base/core/java/android/app/Activity.java
中的startActivity方法启动了对应的应用程序。startActivity
方法是通过调用startActivityForResult方法来实现的。startActivityForResult
方法最终调用了/frameworks/base/core/java/android/app/Instrumentation.java
的execStartActivity方法public class Activity {
@Override
public void startActivity(Intent intent) {
this.startActivity(intent, null);
}
@Override
public void startActivity(Intent intent, @Nullable Bundle options) {
if (options != null) {
startActivityForResult(intent, -1, options);
} else {
startActivityForResult(intent, -1);
}
}
@Override
public void startActivityForResult(...) {
if (mParent == null) {
options = transferSpringboardActivityOptions(options);
// 调用Instrumentation的execStartActivity方法
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(...);
}
}
}
frameworks/base/core/java/android/app/Instrumentation.java 源码地址
Instrumentation.java
中的execStartActivity方法是Activity启动流程的关键。// Instrumentation中有多个execStartActivity同名方法,注意是target的类型为Activity的方法
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
// ActivityTaskManager.getService()获取到ActivityTaskManagerService的实例对象
// 调用ActivityTaskManagerService.startActivity
int result = ActivityTaskManager.getService()
.startActivity(...);
}
/frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java 源码地址
ActivityTaskManagerService
是一个系统服务,负责管理Activity的启动。ActivityStartController
的obtainStarter方法获取了ActivityStarter
对象实例,并调用ActivityStarter
的execute
方法public final int startActivity(...) {
// 调用startActivityAsUser方法
return startActivityAsUser(...);
}
public final int startActivityAsUser(...) {
// ActivityStartController的obtainStarter获取了ActivityStarter对象
return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
... // 构造参数
.execute();
}
/frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java 源码地址
ActivityStarter
中最终会调用RootWindowContainer
的resumeFocusedTasksTopActivities方法int execute() {
// 调用executeRequest方法
res = executeRequest(mRequest);
}
private int executeRequest(Request request) {
// 创建ActivityRecord对象
final ActivityRecord r = new ActivityRecord.Builder(mService)
.setCaller(callerApp)
... // 构造参数
.build();
// 调用startActivityUnchecked方法
mLastStartActivityResult = startActivityUnchecked(...);
}
private int startActivityUnchecked(...) {
// 调用startActivityInner
result = startActivityInner(...);
}
int startActivityInner(...) {
// 调用RootWindowContainer的resumeFocusedTasksTopActivities方法
mRootWindowContainer.resumeFocusedTasksTopActivities(...);
}
/frameworks/base/services/core/java/com/android/server/wm/RootWindowContainer.java 源码地址
RootWindowContainer
是WindowManagerService的主要组成部分之一,是一个管理窗口的容器。Task
和TaskFragment
将前台程序Pause,为新的应用程序启动做准备。Task
的resumeTopActivityUncheckedLocked方法。
private boolean resumeFocusedTasksTopActivities(...) {
// 调用Task的resumeTopActivityUncheckedLocked方法
result = targetRootTask.resumeTopActivityUncheckedLocked(...);
}
/frameworks/base/services/core/java/com/android/server/wm/Task.java 源码地址
Task
最终调用TaskFragment
的resumeTopActivity方法@GuardedBy("mService")
boolean resumeTopActivityUncheckedLocked(...) {
// 调用resumeTopActivityInnerLocked
someActivityResumed = resumeTopActivityInnerLocked(...);
}
@GuardedBy("mService")
private boolean resumeTopActivityInnerLocked(...) {
final TaskFragment topFragment = topActivity.getTaskFragment();
// 调用TaskFragment的resumeTopActivity
resumed[0] = topFragment.resumeTopActivity(...););
return resumed[0];
}
/frameworks/base/services/core/java/com/android/server/wm/TaskFragment.java 源码地址
TaskFragment
最终调用ActivityTaskManagerService
的startProcessAsync方法final boolean resumeTopActivity(...) {
// 暂停当前窗口的Aciticity,可参见源码
...
// 调用ActivityTaskManagerService的startProcessAsync方法创建新的Activity
ActivityTaskManagerService的startProcessAsync方法
mAtmService.startProcessAsync(...);
}
/frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java 源码地址
ActivityTaskManagerService
ActivityManagerInternal
的startProcess方法ActivityManagerInternal
的实现类是ActivityManagerService
// mAmInternal的获取方法,注册方法在ActivityManagerService中(下一小节2.8做介绍)
mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
void startProcessAsync(...) {
// PooledLambda会自动调用mAmInternal(ActivityManagerInternal)的startProcess方法
final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess, mAmInternal, ...);
mH.sendMessage(m);
}
ActivityManagerService.java
中实现/frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java 源码地址
ActivityManagerService
最终调用ProcessList
的startProcessLocked方法public class ActivityManagerService extends IActivityManager.Stub {
// 初始化LocalService(ActivityManagerInternal)
private final ActivityManagerInternal mInternal = new LocalService();
public void init() {
// 在LocalServices中进行注册
LocalServices.addService(ActivityManagerInternal.class, mInternal);
}
private class LocalService extends ActivityManagerInternal {
// ActivityManagerInternal 接口方法的具体实现
@Override
public void startProcess(...) {
synchronized (ActivityManagerService.this) {
// 调用ActivityManagerService的startProcessLocked方法
startProcessLocked(...)
}
}
}
@GuardedBy("this")
final ProcessRecord startProcessLocked(...) {
// 调用ProcessList的startProcessLocked
return mProcessList.startProcessLocked(...);
}
}
/frameworks/base/services/core/java/com/android/server/am/ProcessList.java 源码地址
ProcessList
最终调用到ZygoteProcess
的start方法@GuardedBy("mService")
boolean startProcessLocked(ProcessRecord app, ...) {
// 定义创建Activity完成后回调的入口点(重要)
final String entryPoint = "android.app.ActivityThread";
return startProcessLocked(hostingRecord, ...);
}
@GuardedBy("mService")
boolean startProcessLocked(HostingRecord hostingRecord, ...) {
// 调用startProcess
final Process.ProcessStartResult startResult = startProcess(...);
}
private Process.ProcessStartResult startProcess(...) {
// 获取AppZygote
final AppZygote appZygote = createAppZygoteForProcessIfNeeded(app);
// appZygote.getProcess()获取到ChildZygoteProcess类(ZygoteProcess的子类)
// 调用ZygoteProcess的start方法
startResult = appZygote.getProcess().start(entryPoint,...);
}
/frameworks/base/core/java/android/os/ZygoteProcess.java 源码地址
ZygoteProcess
发送消息给Zygote进程
,通过Zygote进程
创建新的activity进程public final Process.ProcessStartResult start(...) {
// 调用startViaZygote
return startViaZygote(...)
}
private Process.ProcessStartResult startViaZygote(...) {
// 通过openZygoteSocketIfNeeded(abi)打开一个到Zygote进程的套接字连接(Socket)。
// 调用zygoteSendArgsAndGetResult
return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi),zygotePolicyFlags,argsForZygote);
}
@GuardedBy("mLock")
private Process.ProcessStartResult zygoteSendArgsAndGetResult(...) {
// 调用attemptZygoteSendArgsAndGetResult
return attemptZygoteSendArgsAndGetResult(...);
}
private Process.ProcessStartResult attemptZygoteSendArgsAndGetResult(...) {
try {
// 创建Zygote套接字的输入输出流
final BufferedWriter zygoteWriter = zygoteState.mZygoteOutputWriter;
final DataInputStream zygoteInputStream = zygoteState.mZygoteInputStream;
// 发送消息给 Zygote 进程
zygoteWriter.write(msgStr);
zygoteWriter.flush();
// 读取 Zygote 进程返回的结果
Process.ProcessStartResult result = new Process.ProcessStartResult();
result.pid = zygoteInputStream.readInt();
result.usingWrapper = zygoteInputStream.readBoolean();
// 检查 PID 是否有效
if (result.pid < 0) {
throw new ZygoteStartFailedEx("fork() failed");
}
return result;
} catch (IOException ex) {
zygoteState.close();
Log.e(LOG_TAG, "IO Exception while communicating with Zygote - "
+ ex.toString());
throw new ZygoteStartFailedEx(ex);
}
}
在Android启动过程-万字长文(Android14)介绍了Zygote进程(孵化器进程)
ZygoteInit
类中的main方法。下面将简单介绍在Zygote进程的代码流转。
Zygote
进程是在Android系统启动过程中创建的,创建完成后会通过ZygoteServer
来监听消息public static void main(String argv[]) {
ZygoteServer zygoteServer = new ZygoteServer();
...
// 启动Zygote服务器,循环监听消息
caller = zygoteServer.runSelectLoop(abiList);
if (caller != null) {
// 有新的消息就执行对应Runnable代码
caller.run();
}
...
}
ZygoteServer
获取到消息后会调用ZygoteConnection
的processCommand方法Runnable runSelectLoop(String abiList) {
while (true) {
// 使用 select 监听套接字
StructPollfd[] pollFDs = new StructPollfd[socketFDs.size()];
if (pollIndex == 0) {
// 接收到新的连接
ZygoteConnection newPeer = acceptCommandPeer(abiList);
peers.add(newPeer);
socketFDs.add(newPeer.getFileDescriptor());
} else {
// 处理已有连接的请求
ZygoteConnection connection = peers.get(pollIndex);
final Runnable command = connection.processCommand(this, multipleForksOK);
}
}
}
ZygoteConnection
的processCommand方法最终调用ZygoteInit
的zygoteInit方法
Runnable processCommand(ZygoteServer zygoteServer, boolean multipleOK) {
...
// 调用Zygote的forkAndSpecialize方法fork出Acitivity的进程
pid = Zygote.forkAndSpecialize(...);
if (pid == 0) {
// 在子进程中,即创建出来的应用程序所在进程
return handleChildProc(parsedArgs, childPipeFd,
parsedArgs.mStartChildZygote);
} else {
// 在父线程中,pid为创建好的子进程的id
handleParentProc(pid, serverPipeFd);
return null;
}
}
private void handleParentProc(int pid, FileDescriptor serverPipeFd) {
// 通过套接字Socket将子进程的 PID 返回给请求方(ActivityManagerService)
os.writeInt(pid);
}
private Runnable handleChildProc(...) {
// 子进程负责应用程序后续的初始化工作
ZygoteInit.zygoteInit(...)
}
RuntimeInit.applicationInit
方法,进行应用程序的初始化过程public static Runnable zygoteInit(...) {
// 常见的初始化工作,例如设置系统属性、初始化默认的未捕获异常处理器等
RuntimeInit.commonInit();
// Zygote相关的初始化工作。这个初始化过程在C/C++层面进行,设置了必要的Zygote运行环境
ZygoteInit.nativeZygoteInit();
// 调用RuntimeInit.applicationInit方法,进行应用程序的初始化过程
return RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv, classLoader);
}
RuntimeInit
的applicationInit方法完成初始化工作后,通过反射的方式,调用android.app.ActivityThread
的main方法2.9 ProcessList.java
源码中的entryPoint(android.app.ActivityThread
)protected static Runnable applicationInit(...) {
// 查找并返回应用程序的主方法
return findStaticMain(args.startClass, args.startArgs, classLoader);
}
private static Runnable findStaticMain(...) {
// 反射得到android.app.ActivityThread类
cl = Class.forName(className, true, classLoader);
// 反射获取main方法
m = cl.getMethod("main", new Class[] { String[].class });
// 返回可被执行的Runnable对象
return new MethodAndArgsCaller(m, argv);
}
通过Zygote进程
fork出应用程序的进程后,下一步就是创建整个应用程序的Application实例
public static void main(String[] args) {
// 初始化主线模块
initializeMainlineModules();
// 创建MainLooper
Looper.prepareMainLooper();
// 创建ActivityThread
ActivityThread thread = new ActivityThread();
// 创建应用程序Application实例
thread.attach(false, startSeq);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
// 循环监听消息
Looper.loop();
}
@UnsupportedAppUsage
private void attach(boolean system, long startSeq) {
// 获取ActivityManagerService实例
final IActivityManager mgr = ActivityManager.getService();
// 调用ActivityManagerService的attachApplication方法
mgr.attachApplication(mAppThread, startSeq);
}
ActivityManagerService
完成Application创建和第一个Activity的创建@Override
public final void attachApplication(IApplicationThread thread, long startSeq) {
// 调用attachApplicationLocked方法
attachApplicationLocked(thread, callingPid, callingUid, startSeq);
}
private void attachApplicationLocked(...) {
// 调用ActivityThread的bindApplication方法创建并绑定Application
thread.bindApplication(...)
// 在结束Application创建后调用finishAttachApplicationInner启动app的第一个Activity页面,在4.5会介绍这一部分代码
finishAttachApplicationInner(startSeq, callingUid, pid);
}
public final void bindApplication(...) {
AppBindData data = new AppBindData();
... // 构造data的数据
// H为Handler, BIND_APPLICATION是int值
sendMessage(H.BIND_APPLICATION, data);
}
// ActivityThread的内部类H
class H extends Handler {
public void handleMessage(Message msg) {
switch (msg.what) {
case BIND_APPLICATION:
AppBindData data = (AppBindData)msg.obj;
handleBindApplication(data);
break;
}
}
}
@UnsupportedAppUsage
private void handleBindApplication(AppBindData data) {
Application app;
// 最终调用LoadedApk的makeApplicationInner方法加载apk文件到内存中
app = data.info.makeApplicationInner(data.restrictedBackupMode, null);
// 调用Application的onCreate方法,正式进入apk执行文件
mInstrumentation.callApplicationOnCreate(app);
}
private Application makeApplicationInner(...) {
// 获取app的application类(在AndroidManifast.xml中定义的),没有就使用默认的android.app.Application
String appClass = mApplicationInfo.getCustomApplicationClassNameForProcess(
myProcessName);
if (forceDefaultAppClass || (appClass == null)) {
appClass = "android.app.Application";
}
// 调用Instrumentation的newApplication方法创建Application对象
app = mActivityThread.mInstrumentation.newApplication(
cl, appClass, appContext);
}
Instrumentation
完成Application实例的初始化,并调用onCreate方法// 创建Application对象
static public Application newApplication(Class<?> clazz, Context context) {
// Application实例的初始化
Application app = (Application)clazz.newInstance();
app.attach(context);
return app;
}
// 调用Application的onCreate方法
public void callApplicationOnCreate(Application app) {
app.onCreate();
}
ActivityManagerService.java
的attachApplicationLocked方法中LocalService
的attachApplication方法来加载我们的第一个Acitivity页面ActivityTaskManagerInternal
是定义在ActivityTaskManagerService.java
的LocalService
类private void attachApplicationLocked(...) {
// 调用ActivityThread的bindApplication方法创建并绑定Application
thread.bindApplication(...)
// 在结束Application创建后调用finishAttachApplicationInner启动app的第一个Activity页面
finishAttachApplicationInner(startSeq, callingUid, pid);
}
private void finishAttachApplicationInner(long startSeq, int uid, int pid) {
if (normalMode) {
try {
// 调用`ActivityTaskManagerInternal`(即ActivityTaskManagerService.LocalService)的**attachApplication**方法来加载我们的第一个Acitivity页面
didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
}
}
}
RootWindowContainer.attachApplication
方法final class LocalService extends ActivityTaskManagerInternal {
@Override
public boolean attachApplication(WindowProcessController wpc){
// 调用RootWindowContainer的attachApplication
return mRootWindowContainer.attachApplication(wpc);
}
}
ActivityTaskSupervisor
的realStartActivityLocked方法boolean attachApplication(WindowProcessController app) throws RemoteException {
// 调用RootWindowContainer内部类AttachApplicationHelper的process方法
return mAttachApplicationHelper.process(app);
}
private class AttachApplicationHelper implements Consumer<Task>, Predicate<ActivityRecord> {
boolean process(WindowProcessController app) throws RemoteException {
mApp = app;
for (int displayNdx = getChildCount() - 1; displayNdx >= 0; --displayNdx) {
// 通过/frameworks/base/services/core/java/com/android/server/wm/Task.java中的forAllRootTasks调用test方法
getChildAt(displayNdx).forAllRootTasks(this);
}
}
public boolean test(ActivityRecord r) {
// 调用ActivityTaskSupervisor的realStartActivityLocked方法
mTaskSupervisor.realStartActivityLocked(...)
}
}
/frameworks/base/services/core/java/com/android/server/wm/Task.java源码地址
boolean forAllRootTasks(Predicate<Task> callback, boolean traverseTopToBottom) {
// 调用test方法
return isRootTask() ? callback.test(this) : false;
}
boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
boolean andResume, boolean checkConfig) throws RemoteException {
...
// 创建ClientTransaction启动事务:
final ClientTransaction clientTransaction = ClientTransaction.obtain(
proc.getThread(), r.token);
...
// 添加LaunchActivityItem回调
clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent...));
...
// 执行启动事务,调用ClientLifecycleManager的scheduleTransaction方法
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
...
}
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
final IApplicationThread client = transaction.getClient();
// 调用ClientTransaction的schedule
transaction.schedule();
}
public void schedule() throws RemoteException {
// 调用mClient的scheduleTransaction方法
mClient.scheduleTransaction(this);
}
IApplicationThread
接口,实际是ActivityThread的内部类ApplicationThread
对象。ActivityTaskSupervisor的realStartActivityLocked方法
中通过ClientTransaction.obtain(proc.getThread(), r.token),具体可参考ActivityTaskSupervisor源码private class ApplicationThread extends IApplicationThread.Stub {
@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
// 调用ActivityThread的scheduleTransaction
ActivityThread.this.scheduleTransaction(transaction);
}
}
ActivityThread父类ClientTransactionHandler
的scheduleTransaction方法void scheduleTransaction(ClientTransaction transaction) {
transaction.preExecute(this);
// 将事务放入消息队列中,等待主线程的处理
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}
public void handleMessage(Message msg) {
switch (msg.what) {
case EXECUTE_TRANSACTION:
final ClientTransaction transaction = (ClientTransaction) msg.obj;
mTransactionExecutor.execute(transaction);
break;
}
}
public void execute(ClientTransaction transaction) {
// 执行事务中的回调和生命周期状态请求
executeCallbacks(transaction);
executeLifecycleState(transaction);
}
public void executeCallbacks(ClientTransaction transaction) {
final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
// 遍历事务中的所有回调项,并调用每个回调项的execute方法。
for (int i = 0, size = callbacks.size(); i < size; ++i) {
final ClientTransactionItem item = callbacks.get(i);
item.execute(mClient, mTransactionHandler, transaction.getLifecycleStateRequest());
}
}
LaunchActivityItem
的execute方法@Override
public void execute(ClientTransactionHandler client, IBinder token, PendingTransactionActions pendingActions) {
client.handleLaunchActivity(new LaunchActivityItem.ActivityClientRecord(this), pendingActions, null);
}
ActivityThread
的handleLaunchActivity方法public Activity handleLaunchActivity(ActivityClientRecord r, PendingTransactionActions pendingActions, Intent customIntent) {
// 调用performLaunchActivity
final Activity a = performLaunchActivity(r, customIntent);
}
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
// 创建activity对象
activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);
}
public Activity newActivity(...) {
// 创建Activity
Activity activity = (Activity)clazz.newInstance();
...
return activity;
}
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
// 创建activity对象
activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);
// activity绑定上下文Context
activity.attach(appContext, this, getInstrumentation(), r.token,...);
// 调用Instrumentation的callActivityOnCreate方法
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
}
public void callActivityOnCreate(Activity activity, Bundle icicle) {
// 调用Activity的performCreate方法
activity.performCreate(icicle);
}
final void performCreate(...) {
// 调用onCreate方法
if (persistentState != null) {
onCreate(icicle, persistentState);
} else {
onCreate(icicle);
}
}
public void execute(ClientTransaction transaction) {
// 执行事务中的回调
executeCallbacks(transaction);
// 执行生命周期
executeLifecycleState(transaction);
}
public void executeLifecycleState(ClientTransaction transaction) {
final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
if (lifecycleItem != null) {
// 调用ActivityLifecycleItem的execute方法
lifecycleItem.execute(transaction.getClientTransactionHandler(), token, pendingActions);
}
}
ActivityResultItem
是一个抽象类ActivityResultItem
的execute方法public void execute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
client.handleResumeActivity(token, true /* isForward */, "RESUME_ACTIVITY");
}
ActivityThread
的handleResumeActivity方法public void handleResumeActivity(IBinder token, boolean finalStateRequest, String reason) {
// 先调用ActivityThread的performStart方法
performRestartActivity(r);
// 再调用Activity的performResume
r.activity.performResume();
}
public void performRestartActivity(ActivityClientRecord r) {
// 调用Activity的performStart
r.activity.performStart();
}
final void performStart() {
// 调用Instrumentation的callActivityOnStart方法
mInstrumentation.callActivityOnStart(this);
}
public void callActivityOnStart(Activity activity) {
activity.onStart();
}
在5.7.2.3 ActivityThread的handleResumeActivity方法
中提到在onStart方法执行后会调用r.activity.performResume();
即Activity的performResume方法
final void performResume(boolean followedByPause, String reason) {
mInstrumentation.callActivityOnResume(this);
}
public void callActivityOnResume(Activity activity) {
activity.onResume();
}
在生命周期完成后,应用程序就会被展示在屏幕上,后续的工作主要是渲染,这里做一个简单的流程说明
以上就是应用程序启动的全过程,如有错漏,欢迎留言讨论。