Skytoby

AMS启动流程分析

AMS启动流程分析

基于Android10.0,分析AMS的启动过程

一、概述

ActivityManagerService(简称AMS),是Android系统中核心服务之一,负责管理四大组件和应用进程的工作,如四大组件的启动、切换、调度,应用进程的调度等。AMS类图如下:

AMS

ActivityManager通过ActivityManagerNative的getDefault方法得到IActivityManager,通过它可以和AMS进行通信。在之前讲过SystemServer启动过程,本文将从SystemServer启动过程中分析AMS的启动过程。

二、启动分析

SystemServer中主要的三个方法, startBootstrapServices()、startCoreServices()、startOtherServices(),在这三个方法中和AMS相关的如下:

2.1 startBootstrapServices

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
private void startBootstrapServices() {
...
//启动AMS
// Activity manager runs the show.
mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();
//设置AMS的系统管理器
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
//设置AMS的Installer,和PKMS类似,负责执行AMS相关的任务
mActivityManagerService.setInstaller(installer);
...
//初始化AMS相关的PMS
// Now that the power manager has been started, let the activity manager
// initialize power management features.
mActivityManagerService.initPowerManagement();
...
//设置systemserver
// Set up the Application instance for the system process and get started.
mActivityManagerService.setSystemProcess();
}

2.2 启动AMS服务

mSystemServiceManager.startService主要功能如下:

  1. 创建ActivityManagerService.Lifecycle对象
  2. 调用Lifecycle.onStart()方法

2.2.1 AMS.Lifecycle

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public static final class Lifecycle extends SystemService {
private final ActivityManagerService mService;

public Lifecycle(Context context) {
super(context);
mService = new ActivityManagerService(context);
}

@Override
public void onStart() {
mService.start();
}

@Override
public void onBootPhase(int phase) {
mService.mBootPhase = phase;
if (phase == PHASE_SYSTEM_SERVICES_READY) {
mService.mBatteryStatsService.systemServicesReady();
mService.mServices.systemServicesReady();
}
}

@Override
public void onCleanupUser(int userId) {
mService.mBatteryStatsService.onCleanupUser(userId);
}

public ActivityManagerService getService() {
return mService;
}
}

创建内部类Lifecycle,已经创建AMS对象,并调用AMS.start

2.2.2 AMS创建

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
// Note: This method is invoked on the main thread but may need to attach various
// handlers to other threads. So take care to be explicit about the looper.
public ActivityManagerService(Context systemContext) {
LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
mInjector = new Injector();
mContext = systemContext;

mFactoryTest = FactoryTest.getMode();
//创建ActivityThread
mSystemThread = ActivityThread.currentActivityThread();
mUiContext = mSystemThread.getSystemUiContext();

Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());

mPermissionReviewRequired = mContext.getResources().getBoolean(
com.android.internal.R.bool.config_permissionReviewRequired);
//创建名为ActivityManager的前台线程,并获取mHandler
mHandlerThread = new ServiceThread(TAG,
THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
mHandlerThread.start();
mHandler = new MainHandler(mHandlerThread.getLooper());
mUiHandler = mInjector.getUiHandler(this);

//创建ProcStart的前台线程,并获取handler
mProcStartHandlerThread = new ServiceThread(TAG + ":procStart",
THREAD_PRIORITY_FOREGROUND, false /* allowIo */);
mProcStartHandlerThread.start();
mProcStartHandler = new Handler(mProcStartHandlerThread.getLooper());

mConstants = new ActivityManagerConstants(this, mHandler);

/* static; one-time init here */
if (sKillHandler == null) {
//创建SKill的前台进程,并获取handler
sKillThread = new ServiceThread(TAG + ":kill",
THREAD_PRIORITY_BACKGROUND, true /* allowIo */);
sKillThread.start();
sKillHandler = new KillHandler(sKillThread.getLooper());
}

//前台广播接收器,运行超过10s放弃运行
mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
"foreground", BROADCAST_FG_TIMEOUT, false);
//后台广播接收器,运行超过60s放弃运行
mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
"background", BROADCAST_BG_TIMEOUT, true);
mBroadcastQueues[0] = mFgBroadcastQueue;
mBroadcastQueues[1] = mBgBroadcastQueue;

//创建ActiveServices,
//其中非低内存的终端mMaxStartingBackground(后台允许同时执行的service个数)为8,否则为1
mServices = new ActiveServices(this);
mProviderMap = new ProviderMap(this);
mAppErrors = new AppErrors(mUiContext, this);

//创建/data/system
File dataDir = Environment.getDataDirectory();
File systemDir = new File(dataDir, "system");
systemDir.mkdirs();

mAppWarnings = new AppWarnings(this, mUiContext, mHandler, mUiHandler, systemDir);

//创建电池统计服务
// TODO: Move creation of battery stats service outside of activity manager service.
mBatteryStatsService = new BatteryStatsService(systemContext, systemDir, mHandler);
mBatteryStatsService.getActiveStatistics().readLocked();
mBatteryStatsService.scheduleWriteToDisk();
mOnBattery = DEBUG_POWER ? true
: mBatteryStatsService.getActiveStatistics().getIsOnBattery();
mBatteryStatsService.getActiveStatistics().setCallback(this);

//创建进程统计服务,信息在/data/system/procstats
mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
//应用操作服务
mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);

mGrantFile = new AtomicFile(new File(systemDir, "urigrants.xml"), "uri-grants");
//创建UserController,User 0是开机的第一用户
mUserController = new UserController(this);
//创建VrController,VR mode相关
mVrController = new VrController(this);

GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
ConfigurationInfo.GL_ES_VERSION_UNDEFINED);

if (SystemProperties.getInt("sys.use_fifo_ui", 0) != 0) {
mUseFifoUiScheduling = true;
}

mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
mTempConfig.setToDefaults();
mTempConfig.setLocales(LocaleList.getDefault());
mConfigurationSeq = mTempConfig.seq = 1;
//创建ActivityStackSupervisor
mStackSupervisor = createStackSupervisor();
mStackSupervisor.onConfigurationChanged(mTempConfig);

//keyguard管理
mKeyguardController = mStackSupervisor.getKeyguardController();
mCompatModePackages = new CompatModePackages(this, systemDir, mHandler);
//Intent匹配
mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
mTaskChangeNotificationController =
new TaskChangeNotificationController(this, mStackSupervisor, mHandler);
//管理代理activity的启动
mActivityStartController = new ActivityStartController(this);

//创建最近的任务对象,并初始化
mRecentTasks = createRecentTasks();
mStackSupervisor.setRecentTasks(mRecentTasks);
//LockTask管理
mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mHandler);
mLifecycleManager = new ClientLifecycleManager();

//创建名为CpuTracker的线程
mProcessCpuThread = new Thread("CpuTracker") {
@Override
public void run() {
synchronized (mProcessCpuTracker) {
//cpu使用情况跟踪器初始化
mProcessCpuInitLatch.countDown();
mProcessCpuTracker.init();
}
while (true) {
try {
try {
synchronized(this) {
final long now = SystemClock.uptimeMillis();
long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
//Slog.i(TAG, "Cpu delay=" + nextCpuDelay
// + ", write delay=" + nextWriteDelay);
if (nextWriteDelay < nextCpuDelay) {
nextCpuDelay = nextWriteDelay;
}
if (nextCpuDelay > 0) {
mProcessCpuMutexFree.set(true);
this.wait(nextCpuDelay);
}
}
} catch (InterruptedException e) {
}
//更新CPU状态
updateCpuStatsNow();
} catch (Exception e) {
Slog.e(TAG, "Unexpected exception collecting process stats", e);
}
}
}
};
//初始化HiddenApi配置
mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext);

//AMS添加看门口
Watchdog.getInstance().addMonitor(this);
Watchdog.getInstance().addThread(mHandler);

//更新adj
// bind background thread to little cores
// this is expected to fail inside of framework tests because apps can't touch cpusets directly
// make sure we've already adjusted system_server's internal view of itself first
updateOomAdjLocked();
try {
//设置后台线程到THREAD_GROUP_BG_NONINTERACTIVE组
Process.setThreadGroupAndCpuset(BackgroundThread.get().getThreadId(),
Process.THREAD_GROUP_BG_NONINTERACTIVE);
} catch (Exception e) {
Slog.w(TAG, "Setting background thread cpuset failed");
}

}

这个过程创建了五个线程,分别名为ActivityManager、Android.ui、ProcStart、SKill、CpuTracker的线程。

2.2.3 AMS.start

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
private void start() {
//移除所有进程组
removeAllProcessGroups();
//启动CpuTracker线程
mProcessCpuThread.start();

//启动电池统计服务
mBatteryStatsService.publish();
//启动应用操作服务
mAppOpsService.publish(mContext);
Slog.d("AppOps", "AppOpsService published");
//创建LocalService
LocalServices.addService(ActivityManagerInternal.class, new LocalService());
// Wait for the synchronized block started in mProcessCpuThread,
// so that any other acccess to mProcessCpuTracker from main thread
// will be blocked during mProcessCpuTracker initialization.
try {
//等待ProcessCpuTracker初始化
mProcessCpuInitLatch.await();
} catch (InterruptedException e) {
Slog.wtf(TAG, "Interrupted wait during start", e);
Thread.currentThread().interrupt();
throw new IllegalStateException("Interrupted wait during start");
}
}

2.3 AMS.setSystemProcess

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
public void setSystemProcess() {
try {
//添加一些服务,这些服务进程的信息AMS通过binder方式可以获取到
ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false,
DUMP_FLAG_PRIORITY_HIGH);
ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
ServiceManager.addService("dbinfo", new DbBinder(this));
if (MONITOR_CPU_USAGE) {
ServiceManager.addService("cpuinfo", new CpuBinder(this),
/* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
}
ServiceManager.addService("permission", new PermissionController(this));
ServiceManager.addService("processinfo", new ProcessInfoService(this));

ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
"android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());

synchronized (this) {
ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0);
app.persistent = true;
app.pid = MY_PID;
app.maxAdj = ProcessList.SYSTEM_ADJ;
app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
synchronized (mPidsSelfLocked) {
mPidsSelfLocked.put(app.pid, app);
}
updateLruProcessLocked(app, false, null);
updateOomAdjLocked();
}
} catch (PackageManager.NameNotFoundException e) {
throw new RuntimeException(
"Unable to find android system package", e);
}

// Start watching app ops after we and the package manager are up and running.
mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null,
new IAppOpsCallback.Stub() {
@Override public void opChanged(int op, int uid, String packageName) {
if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && packageName != null) {
if (mAppOpsService.checkOperation(op, uid, packageName)
!= AppOpsManager.MODE_ALLOWED) {
runInBackgroundDisabled(uid);
}
}
}
});
}

这个过程主要是注册各种服务。

2.3.1 AT.installSystemApplicationInfo

1
2
3
4
5
6
7
8
9
10
11
public void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) {
synchronized (this) {
//加载名为"android"的package
getSystemContext().installSystemApplicationInfo(info, classLoader);
getSystemUiContext().installSystemApplicationInfo(info, classLoader);

//创建用于性能统计的Profiler对象
// give ourselves a default profiler
mProfiler = new Profiler();
}
}

2.3.2 installSystemApplicationInfo

[-> LoadedApk.java]

1
2
3
4
5
6
7
8
9
10
11
12
/**
* Sets application info about the system package.
*/
void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) {
//将包名为android的ApplicationInfo信息保存
assert info.packageName.equals("android");
mApplicationInfo = info;
mDefaultClassLoader = classLoader;
mAppComponentFactory = createAppFactory(info, mDefaultClassLoader);
mClassLoader = mAppComponentFactory.instantiateClassLoader(mDefaultClassLoader,
new ApplicationInfo(mApplicationInfo));
}

2.4 startCoreServices

1
2
3
4
5
6
7
8
private void startCoreServices() {
...
//初始化AMS相关的UsageStatsManager
// Tracks application usage stats.
mActivityManagerService.setUsageStatsManager(
LocalServices.getService(UsageStatsManagerInternal.class));
...
}

2.5 startOtherServices

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private void startOtherServices() {
...
//初始化系统Providers
mActivityManagerService.installSystemProviders();
...
//初始化AMS的wms
mActivityManagerService.setWindowManager(wm);
...
//安全模式下,添加overlay
if (safeMode) {
mActivityManagerService.showSafeModeOverlay();
}
...
//执行AMS的systemReady
mActivityManagerService.systemReady(goingCallback, traceLog);
}

2.5.1 installSystemProviders

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public final void installSystemProviders() {
List<ProviderInfo> providers;
synchronized (this) {
ProcessRecord app = mProcessNames.get("system", SYSTEM_UID);
//获取provider
providers = generateApplicationProvidersLocked(app);
if (providers != null) {
for (int i=providers.size()-1; i>=0; i--) {
ProviderInfo pi = (ProviderInfo)providers.get(i);
if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Slog.w(TAG, "Not installing system proc provider " + pi.name
+ ": not system .apk");
//移除非系统provider
providers.remove(i);
}
}
}
}
if (providers != null) {
//安装所有的系统provider
mSystemThread.installSystemProviders(providers);
}

synchronized (this) {
mSystemProvidersInstalled = true;
}

mConstants.start(mContext.getContentResolver());
//创建核心SettingsObserver,用于监控Settings的改变
mCoreSettingsObserver = new CoreSettingsObserver(this);
//创建FontScaleSettingObserver,用于监控FontScaleSetting的改变
mFontScaleSettingObserver = new FontScaleSettingObserver();
//创建DevelopmentSettingsObserver,用于监控DevelopmentSettings的改变
mDevelopmentSettingsObserver = new DevelopmentSettingsObserver();
GlobalSettingsToPropertiesMapper.start(mContext.getContentResolver());

// Now that the settings provider is published we can consider sending
// in a rescue party.
RescueParty.onSettingsProviderPublished(mContext);

//mUsageStatsService.monitorPackages();
}

三、ASM.systemReady

AMS.systemReady中有一个Runnable参数goingCallback,这个方法在systemReady中的中间执行,因此在这里将这个方法分为三个过程goingCallback前、中、后。

3.1 before goingCallback

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
traceLog.traceBegin("PhaseActivityManagerReady");
synchronized(this) {
if (mSystemReady) { //首次为flase,不进入分支
// If we're done calling all the receivers, run the next "boot phase" passed in
// by the SystemServer
if (goingCallback != null) {
goingCallback.run();
}
return;
}

mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CANT_SAVE_STATE);
//设备空闲时的服务管理
mLocalDeviceIdleController
= LocalServices.getService(DeviceIdleController.LocalService.class);
mAssistUtils = new AssistUtils(mContext);
mVrController.onSystemReady();

// Make sure we have the current profile info, since it is needed for security checks.
mUserController.onSystemReady();
mRecentTasks.onSystemReadyLocked();
mAppOpsService.systemReady();
//在此设置为ture
mSystemReady = true;
}

try {
//获取device identifiers
sTheRealBuildSerial = IDeviceIdentifiersPolicyService.Stub.asInterface(
ServiceManager.getService(Context.DEVICE_IDENTIFIERS_SERVICE))
.getSerial();
} catch (RemoteException e) {}

ArrayList<ProcessRecord> procsToKill = null;
synchronized(mPidsSelfLocked) {
for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
ProcessRecord proc = mPidsSelfLocked.valueAt(i);
//非persistent进程,加入到procsToKill
if (!isAllowedWhileBooting(proc.info)){
if (procsToKill == null) {
procsToKill = new ArrayList<ProcessRecord>();
}
procsToKill.add(proc);
}
}
}

synchronized(this) {
//杀掉procsToKill列表中的进程,并且不允许重启
if (procsToKill != null) {
for (int i=procsToKill.size()-1; i>=0; i--) {
ProcessRecord proc = procsToKill.get(i);
Slog.i(TAG, "Removing system update proc: " + proc);
removeProcessLocked(proc, true, false, "system update done");
}
}

// Now that we have cleaned up any update processes, we
// are ready to start launching real processes and know that
// we won't trample on them any more.
mProcessesReady = true;
}
//系统处于ready状态
Slog.i(TAG, "System now ready");
EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
SystemClock.uptimeMillis());

synchronized(this) {
// Make sure we have no pre-ready processes sitting around.
//测试状态下启动测试界面
if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) {
ResolveInfo ri = mContext.getPackageManager()
.resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
STOCK_PM_FLAGS);
CharSequence errorMsg = null;
if (ri != null) {
ActivityInfo ai = ri.activityInfo;
ApplicationInfo app = ai.applicationInfo;
if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
mTopAction = Intent.ACTION_FACTORY_TEST;
mTopData = null;
mTopComponent = new ComponentName(app.packageName,
ai.name);
} else {
errorMsg = mContext.getResources().getText(
com.android.internal.R.string.factorytest_not_system);
}
} else {
errorMsg = mContext.getResources().getText(
com.android.internal.R.string.factorytest_no_action);
}
if (errorMsg != null) {
mTopAction = null;
mTopData = null;
mTopComponent = null;
Message msg = Message.obtain();
msg.what = SHOW_FACTORY_ERROR_UI_MSG;
msg.getData().putCharSequence("msg", errorMsg);
mUiHandler.sendMessage(msg);
}
}
}
//恢复Settings
retrieveSettings();
//当前用户id
final int currentUserId = mUserController.getCurrentUserId();
synchronized (this) {
//读取data/system/urigrants.xml文件,获取允许的UriPermission
readGrantedUriPermissionsLocked();
}
//PowerManagerInternal添加本地服务
final PowerManagerInternal pmi = LocalServices.getService(PowerManagerInternal.class);
if (pmi != null) {
//注册LowPowerModeObserver
pmi.registerLowPowerModeObserver(ServiceType.FORCE_BACKGROUND_CHECK,
state -> updateForceBackgroundCheck(state.batterySaverEnabled));
updateForceBackgroundCheck(
pmi.getLowPowerState(ServiceType.FORCE_BACKGROUND_CHECK).batterySaverEnabled);
} else {
Slog.wtf(TAG, "PowerManagerInternal not found.");
}
//进入callback.run
if (goingCallback != null) goingCallback.run();

这个过程中主要的工作如下:

profile info相关的服务执行systemReady;

杀掉procsToKill列表中的进程,并且不允许重启;

此时进程和系统都处于ready状态;

读取UriPermission、注册LowPowerModeObserver。

3.2 goingCallback.run

方法中传递过来的Runnable,开始执行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// We now tell the activity manager it is okay to run third party
// code. It will call back into us once it has gotten to the state
// where third party code can really run (but before it has actually
// started launching the initial applications), for us to complete our
// initialization.
mActivityManagerService.systemReady(() -> {
Slog.i(TAG, "Making services ready");
//phase 550
mSystemServiceManager.startBootPhase(
SystemService.PHASE_ACTIVITY_MANAGER_READY);
try {
mActivityManagerService.startObservingNativeCrashes();
} catch (Throwable e) {
reportWtf("observing native crashes", e);
}
//启动webview
// No dependency on Webview preparation in system server. But this should
// be completed before allowing 3rd party
final String WEBVIEW_PREPARATION = "WebViewFactoryPreparation";
Future<?> webviewPrep = null;
if (!mOnlyCore && mWebViewUpdateService != null) {
webviewPrep = SystemServerInitThreadPool.get().submit(() -> {
Slog.i(TAG, WEBVIEW_PREPARATION);
TimingsTraceLog traceLog = new TimingsTraceLog(
SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
traceLog.traceBegin(WEBVIEW_PREPARATION);
ConcurrentUtils.waitForFutureNoInterrupt(mZygotePreload, "Zygote preload");
mZygotePreload = null;
mWebViewUpdateService.prepareWebViewInSystemServer();
traceLog.traceEnd();
}, WEBVIEW_PREPARATION);
}

if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
traceBeginAndSlog("StartCarServiceHelperService");
mSystemServiceManager.startService(CAR_SERVICE_HELPER_SERVICE_CLASS);
traceEnd();
}
try {
//启动systemUi
startSystemUi(context, windowManagerF);
} catch (Throwable e) {
reportWtf("starting System UI", e);
}
//安全模式下,飞行模式开启
// Enable airplane mode in safe mode. setAirplaneMode() cannot be called
// earlier as it sends broadcasts to other services.
// TODO: This may actually be too late if radio firmware already started leaking
// RF before the respective services start. However, fixing this requires changes
// to radio firmware and interfaces.
if (safeMode) {
try {
connectivityF.setAirplaneMode(true);
} catch (Throwable e) {
reportWtf("enabling Airplane Mode during Safe Mode bootup", e);
}
traceEnd();
}

//主要是网络相关的服务执行systemReady
networkManagementF.systemReady();
networkPolicyF.networkScoreAndNetworkManagementServiceReady();
ipSecServiceF.systemReady();
networkStatsF.systemReady();
connectivityF.systemReady();

//watchdog开启
Watchdog.getInstance().start();

// Wait for all packages to be prepared
mPackageManagerService.waitForAppDataPrepared();
if (webviewPrep != null) {
ConcurrentUtils.waitForFutureNoInterrupt(webviewPrep, WEBVIEW_PREPARATION);
}
//phase 600
mSystemServiceManager.startBootPhase(
SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);

try {
// Note : the network stack is creating on-demand objects that need to send
// broadcasts, which means it currently depends on being started after
// ActivityManagerService.mSystemReady and ActivityManagerService.mProcessesReady
// are set to true. Be careful if moving this to a different place in the
// startup sequence.
NetworkStackClient.getInstance().start(context);
} catch (Throwable e) {
reportWtf("starting Network Stack", e);
}

//一序列服务执行systemRunning
locationF.systemRunning();
countryDetectorF.systemRunning();
networkTimeUpdaterF.systemRunning();
inputManagerF.systemRunning();
telephonyRegistryF.systemRunning();
mediaRouterF.systemRunning();
mmsServiceF.systemRunning();
incident.systemRunning();

}, BOOT_TIMINGS_TRACE_LOG);

这个过程主要的工作如下:

进入到SystemServer phase 550阶段;

启动webview,并且创建进程,这是zygote正式创建的第一个进程;

启动systemui服务;

网络相关的服务执行systemReady;

进入到SystemServer phase 600;

一序列服务执行systemRunning。

3.2.1 startSystemUi

1
2
3
4
5
6
7
8
9
static final void startSystemUi(Context context, WindowManagerService windowManager) {
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.android.systemui",
"com.android.systemui.SystemUIService"));
intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
//Slog.d(TAG, "Starting service: " + intent);
context.startServiceAsUser(intent, UserHandle.SYSTEM);
windowManager.onSystemUiStarted();
}

启动com.android.systemui.SystemUIService服务

3.2 after goingCallback

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
    //统计用户运行时间
mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,
Integer.toString(currentUserId), currentUserId);
//统计用户后台运行时间
mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,
Integer.toString(currentUserId), currentUserId);
//开始执行所有startUser方法
mSystemServiceManager.startUser(currentUserId);

synchronized (this) {
// Only start up encryption-aware persistent apps; once user is
// unlocked we'll come back around and start unaware apps
startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE);

// Start up initial activity.
mBooting = true;
// Enable home activity for system user, so that the system can always boot. We don't
// do this when the system user is not setup since the setup wizard should be the one
// to handle home activity in this case.
if (UserManager.isSplitSystemUser() &&
Settings.Secure.getInt(mContext.getContentResolver(),
Settings.Secure.USER_SETUP_COMPLETE, 0) != 0) {
ComponentName cName = new ComponentName(mContext, SystemUserHomeActivity.class);
try {
AppGlobals.getPackageManager().setComponentEnabledSetting(cName,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0,
UserHandle.USER_SYSTEM);
} catch (RemoteException e) {
throw e.rethrowAsRuntimeException();
}
}
//启动桌面activity
startHomeActivityLocked(currentUserId, "systemReady");

try {
if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
+ " data partition or your device will be unstable.");
mUiHandler.obtainMessage(SHOW_UID_ERROR_UI_MSG).sendToTarget();
}
} catch (RemoteException e) {
}

if (!Build.isBuildConsistent()) {
Slog.e(TAG, "Build fingerprint is not consistent, warning user");
mUiHandler.obtainMessage(SHOW_FINGERPRINT_ERROR_UI_MSG).sendToTarget();
}

long ident = Binder.clearCallingIdentity();
try {
//发送USER_STARTED广播
Intent intent = new Intent(Intent.ACTION_USER_STARTED);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
| Intent.FLAG_RECEIVER_FOREGROUND);
intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
broadcastIntentLocked(null, null, intent,
null, null, 0, null, null, null, OP_NONE,
null, false, false, MY_PID, SYSTEM_UID,
currentUserId);
//发送USER_STARTING广播
intent = new Intent(Intent.ACTION_USER_STARTING);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
broadcastIntentLocked(null, null, intent,
null, new IIntentReceiver.Stub() {
@Override
public void performReceive(Intent intent, int resultCode, String data,
Bundle extras, boolean ordered, boolean sticky, int sendingUser)
throws RemoteException {
}
}, 0, null, null,
new String[] {INTERACT_ACROSS_USERS}, OP_NONE,
null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
} catch (Throwable t) {
Slog.wtf(TAG, "Failed sending first user broadcasts", t);
} finally {
Binder.restoreCallingIdentity(ident);
}
//恢复栈顶的activity
mStackSupervisor.resumeFocusedStackTopActivityLocked();
//发送广播切换到userid
mUserController.sendUserSwitchBroadcasts(-1, currentUserId);

//The limit at which the BinderProxyListener callback will be called
//high:6000 low:5500
BinderInternal.nSetBinderProxyCountWatermarks(6000,5500);
BinderInternal.nSetBinderProxyCountEnabled(true);

BinderInternal.setBinderProxyCountCallback(
new BinderInternal.BinderProxyLimitListener() {
@Override
public void onLimitReached(int uid) {
//超过一定数量的BinderProxy,则killUid
Slog.wtf(TAG, "Uid " + uid + " sent too many Binders to uid "
+ Process.myUid());
BinderProxy.dumpProxyDebugInfo();
if (uid == Process.SYSTEM_UID) {
Slog.i(TAG, "Skipping kill (uid is SYSTEM)");
} else {
killUid(UserHandle.getAppId(uid), UserHandle.getUserId(uid),
"Too many Binders sent to SYSTEM");
}
}
}, mHandler);
}
}

这个过程主要的工作如下:

回调所有SystemService的onStartUser方法;

启动persistent进程;

启动桌面activity;

发送USER_STARTED、USER_STARTING广播;

恢复栈顶Acitvity;

发送广播 UserSwitch;

设置BinderProxyListener。

3.2.1 SSM.startUser

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public void startUser(final int userHandle) {
Slog.i(TAG, "Calling onStartUser u" + userHandle);
final int serviceLen = mServices.size();
for (int i = 0; i < serviceLen; i++) {
final SystemService service = mServices.get(i);
Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "onStartUser "
+ service.getClass().getName());
long time = SystemClock.elapsedRealtime();
try {
//通知所有service,执行onStartUser方法
service.onStartUser(userHandle);
} catch (Exception ex) {
Slog.wtf(TAG, "Failure reporting start of user " + userHandle
+ " to service " + service.getClass().getName(), ex);
}
warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStartUser ");
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
}

3.2.2 startPersistentApps

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void startPersistentApps(int matchFlags) {
if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) return;
synchronized (this) {
try {
//通过PKMS获取所有的persistent进程
final List<ApplicationInfo> apps = AppGlobals.getPackageManager()
.getPersistentApplications(STOCK_PM_FLAGS | matchFlags).getList();
for (ApplicationInfo app : apps) {
if (!"android".equals(app.packageName)) {
//启动persistent进程
addAppLocked(app, null, false, null /* ABI override */);
}
}
} catch (RemoteException ex) {
}
}
}

3.2.3 startHomeActivityLocked

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
boolean startHomeActivityLocked(int userId, String reason) {
if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL
&& mTopAction == null) {
// We are running in factory test mode, but unable to find
// the factory test app, so just sit around displaying the
// error message and don't try to start anything.
return false;
}
//桌面的intent
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.instr == null) {
intent.setFlags(intent.getFlags() | FLAG_ACTIVITY_NEW_TASK);
final int resolvedUserId = UserHandle.getUserId(aInfo.applicationInfo.uid);
// For ANR debugging to verify if the user activity is the one that actually
// launched.
final String myReason = reason + ":" + userId + ":" + resolvedUserId;
//启动桌面activity
mActivityStartController.startHomeActivity(intent, aInfo, myReason);
}
} else {
Slog.wtf(TAG, "No home screen found for " + intent, new Throwable());
}
return true;
}
Intent getHomeIntent() {
Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
intent.setComponent(mTopComponent);
intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
intent.addCategory(Intent.CATEGORY_HOME);
}
return intent;
}

四、总结

1.创建了AMS实例对象,创建了名为ActivityManager、Android.ui、ProcStart、SKill、CpuTracker的线程,创建Context、ActivityThread对象。

2.setSystemProcess主要注册meminfo、gfxinfo、dbinfo 、cpuinfo等服务到ServiceManager,并且更新adj。

3.installSystemProviders加载SystemProviders

4.AMS的systemReady主要是执行相关服务的systemReady,启动sytemui服务,webview,HomeAcitvity

4.1 注册Binder服务

AMS.setSystemProcess过程中向ServiceManager注册了如下Binder服务

服务名 类名 功能
activity ActivityManagerService AMS
procstats ProcessStatsService 进程统计
meminfo MemBinder 内存
gfxinfo GraphicsBinder 图像信息
dbinfo DbBinder 数据库
cpuinfo CpuBinder CPU
permission PermissionController 权限
processinfo ProcessInfoService 进程服务
usagestats UsageStatsService 应用的使用情况

备注:其中UsageStatsService在systemserver的startCoreServices方法,通过setUsageStatsManager注册。

查看这些服务的信息,可以通过dumpsys<服务名>命令。比如查看进程命令

1
dumpsys procstats

4.2 AMS.systemReady

AMS.systemReady大致流程如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) { 
...
//系统处于ready
mSystemReady = true;
...
//杀掉所有非persistent进程
removeProcessLocked(proc, true, false, "system update done");
//进程处于ready
mProcessesReady = true;

goingCallback.run()
//启动persistent进程
startPersistentApps()
//启动homeActivity
startHomeActivityLocked()
//恢复栈顶的activity
mStackSupervisor.resumeFocusedStackTopActivityLocked();
//发送广播切换到userid
mUserController.sendUserSwitchBroadcasts(-1, currentUserId);
...
}

这里说下mProcessesReady,在startProcessLocked过程对于非persistent进程必须等待mProcessesReady=true才会真正的创建进程,否则进程放入mProcessesOnHold队列。以下情况则不会判断mProcessesReady:

addAppLocked启动persistent进程;//此时已经mProcessesReady

finishBooting启动on-hold进程;//此时已经mProcessesReady

cleanUpApplicationRecordLocked;//启动需要restart进程,前提是进程已经创建

attachApplicationLocked;//绑定Bind死亡通告失败,前提同样是进程已经创建

可以看出,mProcessesReady在没有ready之前,基本上没有应用进程。

附录

源码路径

1
2
frameworks/base/core/java/android/app/IActivityManager.aidl
frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java