串联所有核心知识点,深入剖析从Launcher点击图标到应用界面显示的完整流程,理解AMS、WMS、Zygote、Binder等核心服务的协作机制。
引言
经过前26篇的深入学习,我们已经掌握了Android系统的各个核心子系统:
- Binder机制 - 跨进程通信基础
- Zygote与进程孵化 - 应用进程创建
- AMS - Activity和进程生命周期管理
- PMS - 应用包安装与管理
- WMS - 窗口与显示管理
- InputManagerService - 输入事件分发
- PowerManagerService - 电源管理与Doze模式
- NotificationManagerService - 通知管理
- JobScheduler - 任务调度
- ContentProvider - 跨应用数据共享
今天,在这个系列的终篇中,我们将把这些零散的知识点串联起来,完整追踪从用户点击Launcher图标到应用界面显示并响应用户输入的全流程,看看这些核心服务如何协作完成一次完美的应用启动。
这就像是一场精心编排的交响乐:Launcher起奏,AMS指挥,Zygote孕育新生,WMS布置舞台,SurfaceFlinger点亮灯光,最终呈现出一个完整的应用界面。
一、完整流程概览
1.1 核心阶段划分

应用启动可以分为7个核心阶段:
用户交互 → AMS处理 → Zygote孵化 → 应用初始化 → Activity启动 → 窗口创建 → 界面显示
↓ ↓ ↓ ↓ ↓ ↓ ↓
Launcher Intent Socket ActivityThread onCreate addWindow 合成显示
onClick 解析 fork() attachApp onResume Surface 触摸事件
1.2 涉及的核心服务
| 服务 | 职责 | 关键方法 |
|---|---|---|
| Launcher | 桌面应用 | onClick() → startActivity() |
| ActivityManagerService | Activity管理 | startActivity() / startProcessLocked() |
| PackageManagerService | 包信息查询 | resolveIntent() / getActivityInfo() |
| Zygote | 进程孵化 | fork() 系统调用 |
| ApplicationThread | 应用Binder代理 | scheduleLaunchActivity() |
| ActivityThread | 应用主线程 | handleLaunchActivity() |
| WindowManagerService | 窗口管理 | addWindow() / relayoutWindow() |
| SurfaceFlinger | 图形合成 | createSurface() / 图层合成 |
| InputManagerService | 输入分发 | dispatchKey() / dispatchTouch() |
1.3 通信方式
- Binder IPC: Launcher ↔ AMS, AMS ↔ WMS, App ↔ AMS
- Socket: AMS ↔ Zygote (LocalSocket通信)
- 共享内存: App ↔ SurfaceFlinger (GraphicBuffer)
- Handler消息: ActivityThread内部消息循环
二、阶段1:Launcher点击图标
2.1 Launcher界面点击
// packages/apps/Launcher3/src/com/android/launcher3/Launcher.java
public class Launcher extends StatefulActivity<LauncherState> {
// 用户点击应用图标
protected void onClickAppShortcut(View v, ItemInfo item) {
// 1. 获取Intent
Intent intent = item.getIntent();
// 2. 设置启动标志
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// 3. 启动Activity
boolean success = startActivitySafely(v, intent, item);
if (success && v instanceof BubbleTextView) {
// 显示启动动画
mAppTransitionManager.registerRemoteAnimations();
}
}
public boolean startActivitySafely(
View v,
Intent intent,
ItemInfo item) {
// 设置启动选项(动画、窗口大小等)
ActivityOptions opts = makeLaunchOptions(v);
try {
// 调用Context.startActivity()
startActivity(intent, opts.toBundle());
return true;
} catch (ActivityNotFoundException e) {
Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
return false;
} catch (SecurityException e) {
Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
return false;
}
}
}
Intent内容:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setComponent(new ComponentName("com.example.app", "com.example.app.MainActivity"));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2.2 Context.startActivity()
// frameworks/base/core/java/android/app/Activity.java
@Override
public void startActivity(Intent intent, @Nullable Bundle options) {
if (options != null) {
startActivityForResult(intent, -1, options);
} else {
startActivityForResult(intent, -1);
}
}
public void startActivityForResult(
Intent intent,
int requestCode,
@Nullable Bundle options) {
// 通过Instrumentation启动
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, // who
mMainThread.getApplicationThread(), // contextThread
mToken, // token
this, // target
intent, // intent
requestCode, // requestCode
options // options
);
}
2.3 Instrumentation → AMS
// frameworks/base/core/java/android/app/Instrumentation.java
public ActivityResult execStartActivity(
Context who,
IBinder contextThread,
IBinder token,
Activity target,
Intent intent,
int requestCode,
Bundle options) {
// 获取AMS的Binder代理
IActivityTaskManager service = ActivityTaskManager.getService();
try {
// Binder跨进程调用AMS
int result = service.startActivity(
who.getBasePackageName(), // caller
intent, // intent
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, // resultTo
target != null ? target.mEmbeddedID : null,
requestCode, // requestCode
0, // startFlags
null, // profilerInfo
options // options
);
// 检查结果
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
}
return null;
}
关键点:
- Launcher通过Binder IPC调用AMS的startActivity()
- 传递Intent、启动选项、调用者信息
- AMS在system_server进程执行
三、阶段2:AMS处理启动请求

3.1 AMS.startActivity()
// frameworks/base/services/core/java/com/android/server/am/ActivityTaskManagerService.java
@Override
public int startActivity(
IApplicationThread caller,
String callingPackage,
Intent intent,
String resolvedType,
IBinder resultTo,
String resultWho,
int requestCode,
int startFlags,
ProfilerInfo profilerInfo,
Bundle bOptions) {
// 1. 权限检查
enforceNotIsolatedCaller("startActivity");
// 2. 用户ID检查
int userId = mUserController.handleIncomingUser(
Binder.getCallingPid(),
Binder.getCallingUid(),
UserHandle.USER_CURRENT,
"startActivity"
);
// 3. 委托给ActivityStarter处理
return mActivityStartController.obtainStarter(intent, "startActivity")
.setCaller(caller)
.setCallingPackage(callingPackage)
.setResolvedType(resolvedType)
.setResultTo(resultTo)
.setRequestCode(requestCode)
.setStartFlags(startFlags)
.setActivityOptions(bOptions)
.setUserId(userId)
.execute(); // 执行启动
}
3.2 ActivityStarter.execute()
// frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java
int execute() {
try {
// 1. 解析Intent
if (mRequest.intent != null) {
resolveActivity(mRequest);
}
// 2. 执行启动
int res = executeRequest(mRequest);
return res;
} finally {
onExecutionComplete();
}
}
private void resolveActivity(Request request) {
// 通过PMS解析Intent
ResolveInfo rInfo = mSupervisor.resolveIntent(
request.intent,
request.resolvedType,
request.userId
);
if (rInfo == null) {
throw new ActivityNotFoundException(
"Unable to find explicit activity class");
}
// 获取ActivityInfo
ActivityInfo aInfo = rInfo.activityInfo;
request.activityInfo = aInfo;
}
private int executeRequest(Request request) {
// 1. 创建ActivityRecord
ActivityRecord r = new ActivityRecord(
mService,
request.activityInfo,
request.intent,
request.resultTo,
request.userId
);
// 2. 启动Activity
return startActivityUnchecked(r, ...);
}
3.3 启动或创建进程
private int startActivityUnchecked(ActivityRecord r, ...) {
// 1. Task栈管理
TaskRecord taskTop = mTargetStack.topTask();
if (taskTop == null || !taskTop.isSameIntentFilter(r)) {
// 创建新Task
mTargetStack.createTask(r, ...);
}
// 2. 检查进程状态
ProcessRecord app = mService.getProcessRecordLocked(
r.processName,
r.info.applicationInfo.uid
);
if (app != null && app.thread != null) {
// 进程已存在,直接启动Activity
realStartActivityLocked(r, app, ...);
} else {
// 进程不存在,先创建进程
mService.startProcessLocked(
r.processName,
r.info.applicationInfo,
"activity",
r.intent.getComponent()
);
}
return START_SUCCESS;
}
3.4 PMS查询ActivityInfo
// frameworks/base/services/core/java/com/android/server/pm/PackageManagerService.java
@Override
public ResolveInfo resolveIntent(
Intent intent,
String resolvedType,
int flags,
int userId) {
// 1. 查询组件
List<ResolveInfo> query = queryIntentActivitiesInternal(
intent,
resolvedType,
flags,
userId
);
if (query == null || query.size() == 0) {
return null;
}
// 2. 选择最佳匹配
return chooseBestActivity(query, intent);
}
private List<ResolveInfo> queryIntentActivitiesInternal(...) {
ComponentName comp = intent.getComponent();
if (comp != null) {
// 显式Intent,直接查找
ActivityInfo ai = getActivityInfo(comp, flags, userId);
if (ai != null) {
ResolveInfo ri = new ResolveInfo();
ri.activityInfo = ai;
return Collections.singletonList(ri);
}
}
// 隐式Intent,匹配IntentFilter
return mComponentResolver.queryActivities(intent, resolvedType, flags, userId);
}
四、阶段3:Zygote孵化新进程
4.1 AMS请求Zygote
// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
boolean startProcessLocked(
String processName,
ApplicationInfo info,
String hostingType,
ComponentName hostingName) {
return startProcessLocked(
processName,
info,
hostingType,
hostingName,
null /* abiOverride */
);
}
boolean startProcessLocked(...) {
synchronized (this) {
// 1. 创建ProcessRecord
ProcessRecord app = new ProcessRecord(
mService,
info,
processName,
uid
);
// 2. 请求Zygote fork进程
final String entryPoint = "android.app.ActivityThread";
return startProcess(app, entryPoint, ...);
}
}
private boolean startProcess(ProcessRecord app, String entryPoint, ...) {
try {
// 通过Process.start()请求Zygote
final Process.ProcessStartResult startResult = Process.start(
entryPoint, // android.app.ActivityThread
app.processName, // 进程名
uid, // UID
gid, // GID
gids, // 附加GID
runtimeFlags, // 运行标志
mountExternal, // 外部存储挂载模式
app.info.targetSdkVersion, // 目标SDK版本
seInfo, // SELinux信息
abi, // ABI
instructionSet, // 指令集
app.info.dataDir, // 数据目录
invokeWith, // 调试器
app.info.packageName, // 包名
zygoteArgs // Zygote参数
);
// 记录PID
app.pid = startResult.pid;
app.usingWrapper = startResult.usingWrapper;
return true;
} catch (RuntimeException e) {
Log.e(TAG, "Failure starting process " + app.processName, e);
return false;
}
}
4.2 Zygote Socket通信
// frameworks/base/core/java/android/os/Process.java
public static


391

被折叠的 条评论
为什么被折叠?



