本文基于 android-14.0.0_r2 源码
6、system service
SystemServer进程由Zygote进程fork而来,是Zygote孵化出的第一个进程。SystemServer和Zygote进程是Android Framework层的两大重要进程。SystemServer负责启动和管理整个Java frameWork。SystemServer进程在开启的时候,会初始化AMS、WMS、PMS等关键服务。同时会加载本地系统的服务库,调用createSystemContext()创建系统上下文,创建ActivityThread及开启各种服务等等。
SystemServer启动相关代码如下:
// /frameworks/base/services/java/com/android/server/SystemServer.java
/**
* The main entry point from zygote.
*/
public static void main(String[] args) {
new SystemServer().run();
}
...
private void run() {
TimingsTraceAndSlog t = new TimingsTraceAndSlog();
try {
t.traceBegin("InitBeforeStartServices");
// Record the process start information in sys props.
SystemProperties.set(SYSPROP_START_COUNT, String.valueOf(mStartCount));
SystemProperties.set(SYSPROP_START_ELAPSED, String.valueOf(mRuntimeStartElapsedTime));
SystemProperties.set(SYSPROP_START_UPTIME, String.valueOf(mRuntimeStartUptime));
EventLog.writeEvent(EventLogTags.SYSTEM_SERVER_START,
mStartCount, mRuntimeStartUptime, mRuntimeStartElapsedTime);
// Set the device's time zone (a system property) if it is not set or is invalid.
SystemTimeZone.initializeTimeZoneSettingsIfRequired();
// If the system has "persist.sys.language" and friends set, replace them with
// "persist.sys.locale". Note that the default locale at this point is calculated
// using the "-Duser.locale" command line flag. That flag is usually populated by
// AndroidRuntime using the same set of system properties, but only the system_server
// and system apps are allowed to set them.
//
// NOTE: Most changes made here will need an equivalent change to
// core/jni/AndroidRuntime.cpp
// 设置系统语言、国家、时区相关。
if (!SystemProperties.get("persist.sys.language").isEmpty()) {
final String languageTag = Locale.getDefault().toLanguageTag();
SystemProperties.set("persist.sys.locale", languageTag);
SystemProperties.set("persist.sys.language", "");
SystemProperties.set("persist.sys.country", "");
SystemProperties.set("persist.sys.localevar", "");
}
// The system server should never make non-oneway calls
Binder.setWarnOnBlocking(true);
// The system server should always load safe labels
PackageItemInfo.forceSafeLabels();
// Default to FULL within the system server.
SQLiteGlobal.sDefaultSyncMode = SQLiteGlobal.SYNC_MODE_FULL;
// Deactivate SQLiteCompatibilityWalFlags until settings provider is initialized
SQLiteCompatibilityWalFlags.init(null);
// Here we go!
Slog.i(TAG, "Entered the Android system server!");
final long uptimeMillis = SystemClock.elapsedRealtime(); // 开机时间
// 在event.log里输出:"I boot_progress_system_run: 11663",后面的数字代表开机时长,单位ms
EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, uptimeMillis);
if (!mRuntimeRestart) {
FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
FrameworkStatsLog
.BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__SYSTEM_SERVER_INIT_START,
uptimeMillis);
}
// In case the runtime switched since last boot (such as when
// the old runtime was removed in an OTA), set the system
// property so that it is in sync. We can't do this in
// libnativehelper's JniInvocation::Init code where we already
// had to fallback to a different runtime because it is
// running as root and we need to be the system user to set
// the property. http://b/11463182
SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
// Mmmmmm... more memory!
VMRuntime.getRuntime().clearGrowthLimit();
// Some devices rely on runtime fingerprint generation, so make sure
// we've defined it before booting further.
Build.ensureFingerprintProperty();
// Within the system server, it is an error to access Environment paths without
// explicitly specifying a user.
Environment.setUserRequired(true);
// Within the system server, any incoming Bundles should be defused
// to avoid throwing BadParcelableException.
BaseBundle.setShouldDefuse(true);
// Within the system server, when parceling exceptions, include the stack trace
Parcel.setStackTraceParceling(true);
// Ensure binder calls into the system always run at foreground priority.
// 确保系统Binder运行在前台优先级
BinderInternal.disableBackgroundScheduling(true);
// Increase the number of binder threads in system_server
// 设置系统服务的最大Binder线程数为31
BinderInternal.setMaxThreads(sMaxBinderThreads);
// Prepare the main looper thread (this thread).
// 设置 main 线程的优先级,有此可得主线程就是 SystemServer 进程下的其中线程。
android.os.Process.setThreadPriority(
android.os.Process.THREAD_PRIORITY_FOREGROUND);
android.os.Process.setCanSelfBackground(false);
// 开始主线程的运行,和 Looper.loop 配对使用。
// 运行在 Looper.prepareMainLooper() ~ Looper.loop(),之间的就是运行在主线程中
Looper.prepareMainLooper(); // 将当前线程初始化为looper,将其标记为应用程序的主循环。
Looper.getMainLooper().setSlowLogThresholdMs(
SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);
SystemServiceRegistry.sEnableServiceNotFoundWtf = true;
// Initialize native services.
// 初始化本地服务,加载 android_servers 库(libandroid_servers.so)。
System.loadLibrary("android_servers");
// Allow heap / perf profiling.
initZygoteChildHeapProfiling();
// Debug builds - spawn a thread to monitor for fd leaks.
if (Build.IS_DEBUGGABLE) {
spawnFdLeakCheckThread();
}
// Check whether we failed to shut down last time we tried.
// This call may not return.
performPendingShutdown();
// Initialize the system context.
// 1.通过 ActivityThread 来创建 system 上下文。
createSystemContext();
// Call per-process mainline module initialization.
// 初始化 ActivityThread,创建 TelephonyServiceManager、StatsServiceManager、MediaServiceManager。
ActivityThread.initializeMainlineModules();
// Sets the dumper service
// 将 SystemServer 加入 ServiceManager(binder 线程池)。
// 每个继承自 SystemServer 或属于 SystemServer 进程的服务都将加入到 ServiceManager 中的线程池中。
ServiceManager.addService("system_server_dumper", mDumper);
mDumper.addDumpable(this);
// Create the system service manager.
// 每个 server 基本上对应了一个 manager,对外提供的 API 也是只能获取到 manager。
// 2.创建 SystemServiceManagerf服务,它会对系统的服务进行创建、启动和生命周期管理,启动系统的各种服务。
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setStartInfo(mRuntimeRestart,
mRuntimeStartElapsedTime, mRuntimeStartUptime);
mDumper.addDumpable(mSystemServiceManager);
// LocalServices 是 system_server 进程中各个服务提供的本地服务。
// system_server 进程中每个服务都可以往 LocalServices 放对象。
// 有些核心服务是继承自 SystemServer,LocalServices 是公开缓存池目的是解耦。
// 启动SystemServiceManager服务
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
// Prepare the thread pool for init tasks that can be parallelized
// 构建线程池,以便并行执行一些初始化任务
SystemServerInitThreadPool tp = SystemServerInitThreadPool.start();
mDumper.addDumpable(tp);
// Load preinstalled system fonts for system server, so that WindowManagerService, etc
// can start using Typeface. Note that fonts are required not only for text rendering,
// but also for some text operations (e.g. TextUtils.makeSafeForPresentation()).
if (Typeface.ENABLE_LAZY_TYPEFACE_INITIALIZATION) {
Typeface.loadPreinstalledSystemFontMap();
}
// Attach JVMTI agent if this is a debuggable build and the system property is set.
if (Build.IS_DEBUGGABLE) {
// Property is of the form "library_path=parameters".
String jvmtiAgent = SystemProperties.get("persist.sys.dalvik.jvmtiagent");
if (!jvmtiAgent.isEmpty()) {
int equalIndex = jvmtiAgent.indexOf('=');
String libraryPath = jvmtiAgent.substring(0, equalIndex);
String parameterList =
jvmtiAgent.substring(equalIndex + 1, jvmtiAgent.length());
// Attach the agent.
try {
Debug.attachJvmtiAgent(libraryPath, parameterList, null);
} catch (Exception e) {
Slog.e("System", "*************************************************");
Slog.e("System", "********** Failed to load jvmti plugin: " + jvmtiAgent);
}
}
}
} finally {
t.traceEnd(); // InitBeforeStartServices
}
// Setup the default WTF handler
RuntimeInit.setDefaultApplicationWtfHandler(SystemServer::handleEarlySystemWtf);
// Start services.
// 3.启动服务
try {
t.traceBegin("StartServices");
startBootstrapServices(t); // 启动引导服务
startCoreServices(t); // 启动核心服务
startOtherServices(t); // 启动其他服务
// 启动在顶点(Apex)中定义的系统服务,是最后一类启动的服务。在此之后,不得启动任何其他服务。这是为了防止在OTA之外更新这些顶点时出现不必要的稳定性问题;并避免将依赖关系从系统分解为顶点
startApexServices(t);
// Only update the timeout after starting all the services so that we use
// the default timeout to start system server.
updateWatchdogTimeout(t);
// 以上的所有服务都由 mSystemServiceManager 来启动,所以都是继承自 SystemServer。
// 分别是引导服务、核心服务和其他服务
// [引导服务]
// Installer 系统安装 apk 时的一个服务类,启动完成 Installer 服务之后才能启动其他的系统服务。
// ActivityManagerService 负责四大组件的启动、切换、调度。
// PowerManagerService 计算系统中和Power相关的计算,然后决策系统应该如何反应。
// LightsService 管理和显示背光LED。
// DisplayManagerService 用来管理所有显示设备。
// UserManagerService 多用户模式管理。
// SensorService 为系统提供各种感应器服务。
// PackageManagerService 用来对 apk 进行安装、解析、删除、卸载等等操作。
// [核心服务]
// BatteryService 管理电池相关的服务。
// UsageStatsService 收集用户使用每一个 APP 的频率、使用时常。
// WebViewUpdateService WebView 更新服务。
// [其他服务]
// CameraService 摄像头相关服务。
// AlarmManagerService 全局定时器管理服务。
// InputManagerService 管理输入事件。
// WindowManagerService 窗口管理服务。
// VrManagerService VR模式管理服务。
// BluetoothService 蓝牙管理服务。
// NotificationManagerService 通知管理服务。
// DeviceStorageMonitorService 存储相关管理服务。
// LocationManagerService 定位管理服务。
// AudioService 音频相关管理服务。
// [Apex服务]
// Apex服务是指Android操作系统中的一种应用程序启动方式,它允许应用程序在设备启动时以系统服务的形式自动运行。这些服务通常包括系统应用、框架服务和系统UI等。
// 它们在设备启动时会自动运行,并为用户提供各种基础功能和界面。startApexServices方法会遍历所有已安装的Apex服务,并调用它们的启动方法,使它们在系统启动时自动运行。该方法在系统启动过程中被调用,是Android操作系统启动过程中的一部分
} catch (Throwable ex) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting system services", ex);
throw ex;
} finally {
t.traceEnd(); // StartServices
}
StrictMode.initVmDefaults(null);
if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
// 非重启且非第一次开机或者更新时进入
final long uptimeMillis = SystemClock.elapsedRealtime();
FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__SYSTEM_SERVER_READY,
uptimeMillis);
final long maxUptimeMillis = 60 * 1000;
if (uptimeMillis > maxUptimeMillis) {
Slog.wtf(SYSTEM_SERVER_TIMING_TAG,
"SystemServer init took too long. uptimeMillis=" + uptimeMillis);
}
}
// Loop forever.
// 正常情况下,无限循环等待消息
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
这里有几个对象,我们需要分清楚一些:
- SystemServer:Zygote fork出来的一个进程,主要用来管理各类服务;
- SystemService:所有系统服务的父类,例如AMS、WMS、PKMS等都是这个大类的子类;
- SystemServiceManager:属于SystemServer进程,在SystemServer进程启动时创建,SystemServer真正用于管理服务的类,其中startService方法用于启动服务;
- ServiceManager:系统服务大管家,用于跨进程通信,例如app进程想要与AMS通信,那么就需要通过ServerManager来完成进程间通信。
在startOtherServices()方法中会启动SystemUI,之后SystemServer通知AMS系统已准备好,此时AMS启动桌面并且发送BOOT_COMPLETED广播。至此,系统层面启动流程结束。
接下里,我们对和三个步骤进行分析:
6.1 初始化System Context
// /frameworks/base/services/java/com/android/server/SystemServer.java
private void createSystemContext() {
//1.创建ActivityThread对象
ActivityThread activityThread = ActivityThread.systemMain();
//2.获取system context
mSystemContext = activityThread.getSystemContext();
//3.设置系统主题
mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
//4.获取systemui context
final Context systemUiContext = activityThread.getSystemUiContext();
//5.设置systemUI 主题
systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
}
6.1.1systemMain()
systemMain函数主要作用是: 创建ActivityThread对象,然后调用该对象的attach函数。
// /frameworks/base/core/java/android/app/ActivityThread.java
@UnsupportedAppUsage
public static ActivityThread systemMain() {
ThreadedRenderer.initForSystemProcess();
// 1.创建ActivityThread对象
ActivityThread thread = new ActivityThread();
// 2.调用attach方法
thread.attach(true, 0);
return thread;
}
(1)创建ActivityThread对象
ActivityThread是Android Framework中一个非常重要的类,它代表一个应用进程的主线程,其职责就是调度及执行在该线程中运行的四大组件。 注意到此处的ActivityThread创建于SystemServer进程中。
由于SystemServer中也运行着一些系统APK,例如framework-res.apk、SettingsProvider.apk等,因此也可以认为SystemServer是一个特殊的应用进程。
AMS负责管理和调度进程,因此AMS需要通过Binder机制和应用进程通信。 为此,Android提供了一个IApplicationThread接口,该接口定义了AMS和应用进程之间的交互函数。
ActivityThread的构造函数比较简单,获取ResourcesManager的单例对象,比较关键的是它的成员变量:
/**
* This manages the execution of the main thread in an
* application process, scheduling and executing activities,
* broadcasts, and other operations on it as the activity
* manager requests.
*
* {@hide}
*/
public final class ActivityThread extends ClientTransactionHandler
implements ActivityThreadInternal {
...
// 定义了AMS与应用通信的接口,拿到ApplicationThread的对象
@UnsupportedAppUsage
final ApplicationThread mAppThread = new ApplicationThread();
// 拥有自己的looper,说明ActivityThread确实可以代表事件处理线程
@UnsupportedAppUsage
final Looper mLooper = Looper.myLooper();
// H继承Handler,ActivityThread中大量事件处理依赖此Handler
@UnsupportedAppUsage
final H mH = new H();
final Executor mExecutor = new HandlerExecutor(mH);
/**
* Maps from activity token to local record of running activities in this process.
*
* This variable is readable if the code is running in activity thread or holding {@link
* #mResourcesManager}. It's only writable if the code is running in activity thread and holding
* {@link #mResourcesManager}.
*/
//用于保存该进程的ActivityRecord
@UnsupportedAppUsage
final ArrayMap<IBinder, ActivityClientRecord> mActivities = new ArrayMap<>();
...
// 用于保存进程中的Service
@UnsupportedAppUsage
final ArrayMap<IBinder, Service> mServices = new ArrayMap<>();
...
@UnsupportedAppUsage
Application mInitialApplication;
// 用于保存进程中的Application
@UnsupportedAppUsage
final ArrayList<Application> mAllApplications = new ArrayList<>();
...
@UnsupportedAppUsage
public ApplicationThread getApplicationThread()
{
return mAppThread;
}
}
(2)调用attach()方法
对于系统进程而言,ActivityThread的attach函数最重要的工作就是创建了Instrumentation、Application和Context。
// /frameworks/base/core/java/android/app/ActivityThread.java
@UnsupportedAppUsage
private void attach(boolean system, long startSeq) {
sCurrentActivityThread = this;
mConfigurationController = new ConfigurationController(this);
mSystemThread = system;
mStartSeq = startSeq;
// 系统进程system为true
if (!system) {
android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
UserHandle.myUserId());
RuntimeInit.setApplicationObject(mAppThread.asBinder());
final IActivityManager mgr = ActivityManager.getService();
try {
mgr.attachApplication(mAppThread, startSeq);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
// 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)) {
if (DEBUG_MEMORY_TRIM) Slog.d(TAG, "Dalvik max=" + (dalvikMax/1024)
+ " total=" + (runtime.totalMemory()/1024)
+ " used=" + (dalvikUsed/1024));
mSomeActivitiesChanged = false;
try {
ActivityTaskManager.getService().releaseSomeActivities(mAppThread);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
}
});
} else {
// Don't set application object here -- if the system crashes,
// we can't display an alert, we just want to die die die.
android.ddm.DdmHandleAppName.setAppName("system_process",
UserHandle.myUserId());
try {
//系统进程的处理流程,该情况只在SystemServer中处理
//1.创建Instrumentation
mInstrumentation = new Instrumentation();
mInstrumentation.basicInit(this);
//2.创建系统Context
ContextImpl context = ContextImpl.createAppContext(
this, getSystemContext().mPackageInfo);
//3.创建Application
mInitialApplication = context.mPackageInfo.makeApplicationInner(true, null);
mInitialApplication.onCreate();
} catch (Exception e) {
throw new RuntimeException(
"Unable to instantiate Application():" + e.toString(), e);
}
}
- Instrumentation
Instrumentation是Android中的一个工具类,当该类被启用时,它将优先于应用中其它的类被初始化。 此时,系统先创建它,再通过它创建其它组件。
- Context
Context是Android中的一个抽象类,用于维护应用运行环境的全局信息。通过Context可以访问应用的资源和类,甚至进行系统级的操作,例如启动Activity、发送广播等。
- Application
Android中Application类用于保存应用的全局状态。
6.1.2 getSystemContext()
再回到createSystemContext()方法中初始化SystemContext的过程中,到getSystemContext()方法,该方法主要是创建并返回System Context。
// /frameworks/base/core/java/android/app/ActivityThread.java
@Override
@UnsupportedAppUsage
public ContextImpl getSystemContext() {
synchronized (this) {
if (mSystemContext == null) {
// 调用ContextImpl的静态函数createSystemContext()
mSystemContext = ContextImpl.createSystemContext(this);
}
return mSystemContext;
}
}
// /frameworks/base/core/java/android/app/ContextImpl.java
@UnsupportedAppUsage
static ContextImpl createSystemContext(ActivityThread mainThread) {
// 创建LoadedApk类,代表一个加载到系统中的APK
// 注意此时的LoadedApk只是一个空壳
// PKMS还没有启动,无法得到有效的ApplicationInfo
LoadedApk packageInfo = new LoadedApk(mainThread);
// 拿到ContextImpl的对象
ContextImpl context = new ContextImpl(null, mainThread, packageInfo,
ContextParams.EMPTY, null, null, null, null, null, 0, null, null);
// 初始化资源信息
context.setResources(packageInfo.getResources());
context.mResources.updateConfiguration(context.mResourcesManager.getConfiguration(),
context.mResourcesManager.getDisplayMetrics());
context.mContextType = CONTEXT_TYPE_SYSTEM_OR_SYSTEM_UI;
return context;
}
createSystemContext()的内容就是创建一个LoadedApk,然后初始化一个ContextImpl对象。 创建的LoadApk对应packageName为”android”,也就是framwork-res.apk。 由于该APK仅供SystemServer进程使用,因此创建的Context被定义为System Context。
现在该LoadedApk还没有得到framwork-res.apk实际的信息。当PKMS启动,完成对应的解析后,AMS将重新设置这个LoadedApk。
6.1.3 getSystemUiContext()
这个方法是用来获取SystemUi的Context,具体流程与getSystemContext()方法类似。
// /frameworks/base/core/java/android/app/ActivityThread.java
@NonNull
public ContextImpl getSystemUiContext() {
return getSystemUiContext(DEFAULT_DISPLAY);
}
/**
* Gets the context instance base on system resources & display information which used for UI.
* @param displayId The ID of the display where the UI is shown.
* @see ContextImpl#createSystemUiContext(ContextImpl, int)
*/
@NonNull
public ContextImpl getSystemUiContext(int displayId) {
synchronized (this) {
if (mDisplaySystemUiContexts == null) {
mDisplaySystemUiContexts = new SparseArray<>();
}
ContextImpl systemUiContext = mDisplaySystemUiContexts.get(displayId);
if (systemUiContext == null) {
systemUiContext = ContextImpl.createSystemUiContext(getSystemContext(), displayId);
mDisplaySystemUiContexts.put(displayId, systemUiContext);
}
return systemUiContext;
}
}
6.2 创建SystemServiceManager
再回到SystemServer启动的run()方法中,在调用createSystemContext()方法初始化System Context后,就是创建SystemServiceManager对象。
6.2.1 SystemServiceManager()
SystemServiceManager对象主要用于管理SystemService的创建、启动等生命周期,SystemService 类是一个抽象类。
// /frameworks/base/services/core/java/com/android/server/SystemServiceManager.java
/**
* Manages creating, starting, and other lifecycle events of
* {@link com.android.server.SystemService system services}.
*
* {@hide}
*/
public final class SystemServiceManager implements Dumpable {
...
private final Context mContext;
...
// Services that should receive lifecycle events.
private List<SystemService> mServices;
private Set<String> mServiceClassnames;
...
SystemServiceManager(Context context) {
mContext = context;
mServices = new ArrayList<>();
mServiceClassnames = new ArraySet<>();
mNumUserPoolThreads = Math.min(Runtime.getRuntime().availableProcessors(),
DEFAULT_MAX_USER_POOL_THREADS);
}
...
/**
* Starts a service by class name.
*
* @return The service instance.
*/
public SystemService startService(String className) {
// 通过反射根据类名,拿到类对象
final Class<SystemService> serviceClass = loadClassFromLoader(className,
this.getClass().getClassLoader());
return startService(serviceClass);
}
...
/*
* Loads and initializes a class from the given classLoader. Returns the class.
*/
@SuppressWarnings("unchecked")
private static Class<SystemService> loadClassFromLoader(String className,
ClassLoader classLoader) {
try {
return (Class<SystemService>) Class.forName(className, true, classLoader);
} catch (ClassNotFoundException ex) {
throw new RuntimeException("Failed to create service " + className
+ " from class loader " + classLoader.toString() + ": service class not "
+ "found, usually indicates that the caller should "
+ "have called PackageManager.hasSystemFeature() to check whether the "
+ "feature is available on this device before trying to start the "
+ "services that implement it. Also ensure that the correct path for the "
+ "classloader is supplied, if applicable.", ex);
}
}
// 后面具体案例详细解释startService
在SystemServiceManager中都是通过反射创建SystemService中对象的,而且在 startService(@NonNull final SystemService service)方法中,会将SystemService添加到mServices 中,并调用 onStart() 方法。
1.2.2 addService()
回到《6 创建SystemService》中,在创建完SystemServiceManager对象后,run()会调用addService()方法:
// /frameworks/base/core/java/com/android/server/LocalServices.java
/**
* This class is used in a similar way as ServiceManager, except the services registered here
* are not Binder objects and are only available in the same process.
*
* Once all services are converted to the SystemService interface, this class can be absorbed
* into SystemServiceManager.
*
* {@hide}
*/
public final class LocalServices {
private LocalServices() {}
private static final ArrayMap<Class<?>, Object> sLocalServiceObjects =
new ArrayMap<Class<?>, Object>();
/**
* Returns a local service instance that implements the specified interface.
*
* @param type The type of service.
* @return The service object.
*/
// 返回实现指定接口的本地服务实例对象
@SuppressWarnings("unchecked")
public static <T> T getService(Class<T> type) {
synchronized (sLocalServiceObjects) {
return (T) sLocalServiceObjects.get(type);
}
}
/**
* Adds a service instance of the specified interface to the global registry of local services.
*/
// 将指定接口的服务实例添加到本地服务的全局注册表中
public static <T> void addService(Class<T> type, T service) {
synchronized (sLocalServiceObjects) {
if (sLocalServiceObjects.containsKey(type)) {
throw new IllegalStateException("Overriding service registration");
}
sLocalServiceObjects.put(type, service);
}
}
/**
* Remove a service instance, must be only used in tests.
*/
// 删除服务实例,只能在测试中使用
@VisibleForTesting
public static <T> void removeServiceForTest(Class<T> type) {
synchronized (sLocalServiceObjects) {
sLocalServiceObjects.remove(type);
}
}
}
1.3 启动核心服务
回到《6.SystemServer启动》中,在处理完SystemServiceManager对象后,回去启动三个服务,这里首先关心核心服务启动:startBootstrapServices()。
在该方法中启动引导服务,在其中启动了ATM和AMS服务,通过AMS安装Installer、初始化Power,设置系统进程等。
6.3 启动服务
6.3.1 startBootstrapServices
// /frameworks/base/services/java/com/android/server/SystemServer.java
/**
* Starts the small tangle of critical services that are needed to get the system off the
* ground. These services have complex mutual dependencies which is why we initialize them all
* in one place here. Unless your service is also entwined in these dependencies, it should be
* initialized in one of the other functions.
*/
private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
t.traceBegin("startBootstrapServices");
t.traceBegin("ArtModuleServiceInitializer");
// This needs to happen before DexUseManagerLocal init. We do it here to avoid colliding
// with a GC. ArtModuleServiceInitializer is a class from a separate dex file
// "service-art.jar", so referencing it involves the class linker. The class linker and the
// GC are mutually exclusive (b/263486535). Therefore, we do this here to force trigger the
// class linker earlier. If we did this later, especially after PackageManagerService init,
// the class linker would be consistently blocked by a GC because PackageManagerService
// allocates a lot of memory and almost certainly triggers a GC.
ArtModuleServiceInitializer.setArtModuleServiceManager(new ArtModuleServiceManager());
t.traceEnd();
// Start the watchdog as early as possible so we can crash the system server
// if we deadlock during early boot
// 尽早启动看门狗,以便在早期启动过程中出现死锁时使系统服务器崩溃。
t.traceBegin("StartWatchdog");
// 启动看门狗,看门狗需要定时喂狗,若喂狗超时则会触发重启,以便知道进程和服务是否正常运行。
final Watchdog watchdog = Watchdog.getInstance();
watchdog.start();
mDumper.addDumpable(watchdog);
t.traceEnd();
Slog.i(TAG, "Reading configuration...");
final String TAG_SYSTEM_CONFIG = "ReadingSystemConfig";
t.traceBegin(TAG_SYSTEM_CONFIG);
SystemServerInitThreadPool.submit(SystemConfig::getInstance, TAG_SYSTEM_CONFIG);
t.traceEnd();
// Platform compat service is used by ActivityManagerService, PackageManagerService, and
// possibly others in the future. b/135010838.
t.traceBegin("PlatformCompat");
PlatformCompat platformCompat = new PlatformCompat(mSystemContext);
ServiceManager.addService(Context.PLATFORM_COMPAT_SERVICE, platformCompat);
ServiceManager.addService(Context.PLATFORM_COMPAT_NATIVE_SERVICE,
new PlatformCompatNative(platformCompat));
AppCompatCallbacks.install(new long[0]);
t.traceEnd();
// FileIntegrityService responds to requests from apps and the system. It needs to run after
// the source (i.e. keystore) is ready, and before the apps (or the first customer in the
// system) run.
t.traceBegin("StartFileIntegrityService");
mSystemServiceManager.startService(FileIntegrityService.class);
t.traceEnd();
// Wait for installd to finish starting up so that it has a chance to
// create critical directories such as /data/user with the appropriate
// permissions. We need this to complete before we initialize other services.
// 通过 mSystemServiceManager 来启动 Installer 服务,管理应用的安装与卸载。
t.traceBegin("StartInstaller");
Installer installer = mSystemServiceManager.startService(Installer.class);
t.traceEnd();
// In some cases after launching an app we need to access device identifiers,
// therefore register the device identifier policy before the activity manager.
t.traceBegin("DeviceIdentifiersPolicyService");
mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);
t.traceEnd();
// Uri Grants Manager.
// 通过 mSystemServiceManager 来启动 UriGrantsManagerService,管理 Uri。
t.traceBegin("UriGrantsManagerService");
mSystemServiceManager.startService(UriGrantsManagerService.Lifecycle.class);
t.traceEnd();
// 通过 mSystemServiceManager 来启动 PowerStatsService,管理电源状态。
t.traceBegin("StartPowerStatsService");
// Tracks rail data to be used for power statistics.
mSystemServiceManager.startService(PowerStatsService.class);
t.traceEnd();
t.traceBegin("StartIStatsService");
startIStatsService();
t.traceEnd();
// Start MemtrackProxyService before ActivityManager, so that early calls
// to Memtrack::getMemory() don't fail.
t.traceBegin("MemtrackProxyService");
startMemtrackProxyService();
t.traceEnd();
// Start AccessCheckingService which provides new implementation for permission and app op.
t.traceBegin("StartAccessCheckingService");
mSystemServiceManager.startService(AccessCheckingService.class);
t.traceEnd();
// Activity manager runs the show.
// 1.通过 mSystemServiceManager 来启动 ActivityTaskManagerService,管理 Activity 任务栈。
// Android10新引入功能,用来管理Activity的启动、调度等功能
t.traceBegin("StartActivityManager");
// TODO: Might need to move after migration to WM.
ActivityTaskManagerService atm = mSystemServiceManager.startService(
ActivityTaskManagerService.Lifecycle.class).getService();
// 2.启动 AMS,并将 ATMS 注入
mActivityManagerService = ActivityManagerService.Lifecycle.startService(
mSystemServiceManager, atm);
// 3.让 ActivityManagerService 拿到 systemServer,例如可以通过 mSystemServiceManager 来判断系统是否启动完成。
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
// 4.利用atm,获取WindowManagerGlobalLock
mWindowManagerGlobalLock = atm.getGlobalLock();
t.traceEnd();
// Data loader manager service needs to be started before package manager
t.traceBegin("StartDataLoaderManagerService");
mDataLoaderManagerService = mSystemServiceManager.startService(
DataLoaderManagerService.class);
t.traceEnd();
// Incremental service needs to be started before package manager
t.traceBegin("StartIncrementalService");
mIncrementalServiceHandle = startIncrementalService();
t.traceEnd();
// Power manager needs to be started early because other services need it.
// Native daemons may be watching for it to be registered so it must be ready
// to handle incoming binder calls immediately (including being able to verify
// the permissions for those calls).
// 启用 PowerManagerService 服务,电源管理服务。
t.traceBegin("StartPowerManager");
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
t.traceEnd();
t.traceBegin("StartThermalManager");
mSystemServiceManager.startService(ThermalManagerService.class);
t.traceEnd();
t.traceBegin("StartHintManager");
mSystemServiceManager.startService(HintManagerService.class);
t.traceEnd();
// Now that the power manager has been started, let the activity manager
// initialize power management features.
//5.初始化PowerManager
t.traceBegin("InitPowerManagement");
mActivityManagerService.initPowerManagement();
t.traceEnd();
// Bring up recovery system in case a rescue party needs a reboot
t.traceBegin("StartRecoverySystemService");
mSystemServiceManager.startService(RecoverySystemService.Lifecycle.class);
t.traceEnd();
// Now that we have the bare essentials of the OS up and running, take
// note that we just booted, which might send out a rescue party if
// we're stuck in a runtime restart loop.
RescueParty.registerHealthObserver(mSystemContext);
PackageWatchdog.getInstance(mSystemContext).noteBoot();
// Manages LEDs and display backlight so we need it to bring up the display.
// 启动屏幕亮度服务,比如亮度调整。
t.traceBegin("StartLightsService");
mSystemServiceManager.startService(LightsService.class);
t.traceEnd();
t.traceBegin("StartDisplayOffloadService");
// Package manager isn't started yet; need to use SysProp not hardware feature
if (SystemProperties.getBoolean("config.enable_display_offload", false)) {
mSystemServiceManager.startService(WEAR_DISPLAYOFFLOAD_SERVICE_CLASS);
}
t.traceEnd();
t.traceBegin("StartSidekickService");
// Package manager isn't started yet; need to use SysProp not hardware feature
if (SystemProperties.getBoolean("config.enable_sidekick_graphics", false)) {
mSystemServiceManager.startService(WEAR_SIDEKICK_SERVICE_CLASS);
}
t.traceEnd();
// Display manager is needed to provide display metrics before package manager
// starts up.
// 启动屏幕显示服务。
t.traceBegin("StartDisplayManager");
mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
t.traceEnd();
// We need the default display before we can initialize the package manager.
t.traceBegin("WaitForDisplay");
mSystemServiceManager.startBootPhase(t, SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
t.traceEnd();
// Start the package manager.
if (!mRuntimeRestart) {
FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
FrameworkStatsLog
.BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__PACKAGE_MANAGER_INIT_START,
SystemClock.elapsedRealtime());
}
t.traceBegin("StartDomainVerificationService");
DomainVerificationService domainVerificationService = new DomainVerificationService(
mSystemContext, SystemConfig.getInstance(), platformCompat);
mSystemServiceManager.startService(domainVerificationService);
t.traceEnd();
t.traceBegin("StartPackageManagerService");
try {
Watchdog.getInstance().pauseWatchingCurrentThread("packagemanagermain");
// 启动 PMS,包管理服务。
mPackageManagerService = PackageManagerService.main(
mSystemContext, installer, domainVerificationService,
mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF);
} finally {
Watchdog.getInstance().resumeWatchingCurrentThread("packagemanagermain");
}
mFirstBoot = mPackageManagerService.isFirstBoot();
mPackageManager = mSystemContext.getPackageManager();
t.traceEnd();
t.traceBegin("DexUseManagerLocal");
// DexUseManagerLocal needs to be loaded after PackageManagerLocal has been registered, but
// before PackageManagerService starts processing binder calls to notifyDexLoad.
LocalManagerRegistry.addManager(
DexUseManagerLocal.class, DexUseManagerLocal.createInstance(mSystemContext));
t.traceEnd();
if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
FrameworkStatsLog
.BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__PACKAGE_MANAGER_INIT_READY,
SystemClock.elapsedRealtime());
}
// Manages A/B OTA dexopting. This is a bootstrap service as we need it to rename
// A/B artifacts after boot, before anything else might touch/need them.
boolean disableOtaDexopt = SystemProperties.getBoolean("config.disable_otadexopt", false);
if (!disableOtaDexopt) {
t.traceBegin("StartOtaDexOptService");
try {
Watchdog.getInstance().pauseWatchingCurrentThread("moveab");
OtaDexoptService.main(mSystemContext, mPackageManagerService);
} catch (Throwable e) {
reportWtf("starting OtaDexOptService", e);
} finally {
Watchdog.getInstance().resumeWatchingCurrentThread("moveab");
t.traceEnd();
}
}
t.traceBegin("StartUserManagerService");
mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
t.traceEnd();
// Initialize attribute cache used to cache resources from packages.
t.traceBegin("InitAttributerCache");
AttributeCache.init(mSystemContext);
t.traceEnd();
// Set up the Application instance for the system process and get started.
//6.设置系统进程
t.traceBegin("SetSystemProcess");
mActivityManagerService.setSystemProcess();
t.traceEnd();
// The package receiver depends on the activity service in order to get registered.
platformCompat.registerPackageReceiver(mSystemContext);
// Complete the watchdog setup with an ActivityManager instance and listen for reboots
// Do this only after the ActivityManagerService is properly started as a system process
t.traceBegin("InitWatchdog");
watchdog.init(mSystemContext, mActivityManagerService);
t.traceEnd();
// DisplayManagerService needs to setup android.display scheduling related policies
// since setSystemProcess() would have overridden policies due to setProcessGroup
mDisplayManagerService.setupSchedulerPolicies();
// Manages Overlay packages
t.traceBegin("StartOverlayManagerService");
mSystemServiceManager.startService(new OverlayManagerService(mSystemContext));
t.traceEnd();
// Manages Resources packages
t.traceBegin("StartResourcesManagerService");
ResourcesManagerService resourcesService = new ResourcesManagerService(mSystemContext);
resourcesService.setActivityManagerService(mActivityManagerService);
mSystemServiceManager.startService(resourcesService);
t.traceEnd();
t.traceBegin("StartSensorPrivacyService");
mSystemServiceManager.startService(new SensorPrivacyService(mSystemContext));
t.traceEnd();
if (SystemProperties.getInt("persist.sys.displayinset.top", 0) > 0) {
// DisplayManager needs the overlay immediately.
mActivityManagerService.updateSystemUiContext();
LocalServices.getService(DisplayManagerInternal.class).onOverlayChanged();
}
// The sensor service needs access to package manager service, app ops
// service, and permissions service, therefore we start it after them.
// 启动传感器服务。
t.traceBegin("StartSensorService");
mSystemServiceManager.startService(SensorService.class);
t.traceEnd();
t.traceEnd(); // startBootstrapServices
}
mSystemServiceManager.startService
可以看到大多数服务都是通过 mSystemServiceManager.startService 来启动,接下来看看 startService 方法内容。
// /frameworks/base/services/core/java/com/android/server/SystemServiceManager.java
/**
* Creates and starts a system service. The class must be a subclass of
* {@link com.android.server.SystemService}.
*
* @param serviceClass A Java class that implements the SystemService interface.
* @return The service instance, never null.
* @throws RuntimeException if the service fails to start.
*/
public <T extends SystemService> T startService(Class<T> serviceClass) {
try {
final String name = serviceClass.getName();
Slog.i(TAG, "Starting " + name);
Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartService " + name);
// Create the service.
if (!SystemService.class.isAssignableFrom(serviceClass)) {
throw new RuntimeException("Failed to create " + name
+ ": service must extend " + SystemService.class.getName());
}
final T service;
try {
// 反射拿到该 Java 类
Constructor<T> constructor = serviceClass.getConstructor(Context.class);
service = constructor.newInstance(mContext);
} catch (InstantiationException ex) {
throw new RuntimeException("Failed to create service " + name
+ ": service could not be instantiated", ex);
} catch (IllegalAccessException ex) {
throw new RuntimeException("Failed to create service " + name
+ ": service must have a public constructor with a Context argument", ex);
} catch (NoSuchMethodException ex) {
throw new RuntimeException("Failed to create service " + name
+ ": service must have a public constructor with a Context argument", ex);
} catch (InvocationTargetException ex) {
throw new RuntimeException("Failed to create service " + name
+ ": service constructor threw an exception", ex);
}
// 将当前服务(Java类)加入 SystemService 服务队列中,统一管理。
startService(service);
return service;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
}
public void startService(@NonNull final SystemService service) {
// Check if already started
String className = service.getClass().getName();
if (mServiceClassnames.contains(className)) {
Slog.i(TAG, "Not starting an already started service " + className);
return;
}
// 将当前服务加入 mServices 队列中。
mServiceClassnames.add(className);
// Register it.
mServices.add(service);
// Start it.
long time = SystemClock.elapsedRealtime();
try {
// 调用当前服务的 onStart 来启动服务。
service.onStart();
} catch (RuntimeException ex) {
throw new RuntimeException("Failed to start service " + service.getClass().getName()
+ ": onStart threw an exception", ex);
}
warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
}
可以看到 startService 方法就是反射拿到服务类,然后加入队列中,调用其 onStart 方法进行启动。
ServiceManager.onStart 服务管理
每个属于 SystemServer 的服务都将加入到 ServiceManager 的 binder 线程池中,以供后续直接获取和管理。就拿 BatteryService 服务来讲解:
// /frameworks/base/services/core/java/com/android/server/BatteryService.java
@Override
public void onStart() {
registerHealthCallback();
mBinderService = new BinderService();
// 将 BinderService 服务加入 ServiceManager 中。
publishBinderService("battery", mBinderService);
mBatteryPropertiesRegistrar = new BatteryPropertiesRegistrar();
// 将 batteryproperties 服务加入 ServiceManager 中。
publishBinderService("batteryproperties", mBatteryPropertiesRegistrar);
// 将 BinderService 服务加入到 LocalServices 中。
publishLocalService(BatteryManagerInternal.class, new LocalService());
}
...
// 继续看看 mBinderService 具体是什么,又是如何加入到 ServiceManager 中的:
private final class BinderService extends Binder {
@Override protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
if (args.length > 0 && "--proto".equals(args[0])) {
dumpProto(fd);
} else {
dumpInternal(fd, pw, args);
}
}
@Override public void onShellCommand(FileDescriptor in, FileDescriptor out,
FileDescriptor err, String[] args, ShellCallback callback,
ResultReceiver resultReceiver) {
(new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
}
}
可以看到 mBinderService 就是一个 Binder,然后调用 publishBinderService 加入到 ServiceManager 中的 binder 线程池中:
// /frameworks/base/services/core/java/com/android/server/SystemService.java
/**
* Publish the service so it is accessible to other services and apps.
*
* @param name the name of the new service
* @param service the service object
*/
protected final void publishBinderService(@NonNull String name, @NonNull IBinder service) {
publishBinderService(name, service, false);
}
/**
* Publish the service so it is accessible to other services and apps.
*
* @param name the name of the new service
* @param service the service object
* @param allowIsolated set to true to allow isolated sandboxed processes
* to access this service
*/
protected final void publishBinderService(@NonNull String name, @NonNull IBinder service,
boolean allowIsolated) {
publishBinderService(name, service, allowIsolated, DUMP_FLAG_PRIORITY_DEFAULT);
}
/**
* Publish the service so it is accessible to other services and apps.
*
* @param name the name of the new service
* @param service the service object
* @param allowIsolated set to true to allow isolated sandboxed processes
* to access this service
* @param dumpPriority supported dump priority levels as a bitmask
*
* @hide
*/
protected final void publishBinderService(String name, IBinder service,
boolean allowIsolated, int dumpPriority) {
ServiceManager.addService(name, service, allowIsolated, dumpPriority);
}
调用 ServiceManager.addService 加入到 binder 线程池中,而 ServiceManager 服务早就在 servicemanager.rc 文件中作为核心服务启动了
6.3.2startCoreServices
// /frameworks/base/services/java/com/android/server/SystemServer.java
/**
* Starts some essential services that are not tangled up in the bootstrap process.
*/
private void startCoreServices(@NonNull TimingsTraceAndSlog t) {
t.traceBegin("startCoreServices");
// Service for system config
t.traceBegin("StartSystemConfigService");
mSystemServiceManager.startService(SystemConfigService.class);
t.traceEnd();
// 管理电池相关的服务,用于统计电池电量,需要LightService.
t.traceBegin("StartBatteryService");
// Tracks the battery level. Requires LightService.
mSystemServiceManager.startService(BatteryService.class);
t.traceEnd();
// Tracks application usage stats.
// 用于统计应用使用情况
t.traceBegin("StartUsageService");
mSystemServiceManager.startService(UsageStatsService.class);
mActivityManagerService.setUsageStatsManager(
LocalServices.getService(UsageStatsManagerInternal.class));
t.traceEnd();
// Tracks whether the updatable WebView is in a ready state and watches for update installs.
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) {
// 跟踪可更新的WebView是否处于就绪状态,并监视更新安装
t.traceBegin("StartWebViewUpdateService");
mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
t.traceEnd();
}
// Tracks and caches the device state.
// 跟踪和缓存设备状态
t.traceBegin("StartCachedDeviceStateService");
mSystemServiceManager.startService(CachedDeviceStateService.class);
t.traceEnd();
// Tracks cpu time spent in binder calls
// ,跟踪在绑定器调用中花费的cpu时间
t.traceBegin("StartBinderCallsStatsService");
mSystemServiceManager.startService(BinderCallsStatsService.LifeCycle.class);
t.traceEnd();
// Tracks time spent in handling messages in handlers.
// 跟踪处理程序中处理消息所花费的时间
t.traceBegin("StartLooperStatsService");
mSystemServiceManager.startService(LooperStatsService.Lifecycle.class);
t.traceEnd();
// Manages apk rollbacks.
// 管理apk回滚
t.traceBegin("StartRollbackManagerService");
mSystemServiceManager.startService(ROLLBACK_MANAGER_SERVICE_CLASS);
t.traceEnd();
// Tracks native tombstones.
t.traceBegin("StartNativeTombstoneManagerService");
mSystemServiceManager.startService(NativeTombstoneManagerService.class);
t.traceEnd();
// Service to capture bugreports.
// 捕获bugreports的服务
t.traceBegin("StartBugreportManagerService");
mSystemServiceManager.startService(BugreportManagerService.class);
t.traceEnd();
// Service for GPU and GPU driver.
// 硬件显示服务
t.traceBegin("GpuService");
mSystemServiceManager.startService(GpuService.class);
t.traceEnd();
// Handles system process requests for remotely provisioned keys & data.
t.traceBegin("StartRemoteProvisioningService");
mSystemServiceManager.startService(RemoteProvisioningService.class);
t.traceEnd();
// TODO(b/277600174): Start CpuMonitorService on all builds and not just on debuggable
// builds once the Android JobScheduler starts using this service.
if (Build.IS_DEBUGGABLE || Build.IS_ENG) {
// Service for CPU monitor.
t.traceBegin("CpuMonitorService");
mSystemServiceManager.startService(CpuMonitorService.class);
t.traceEnd();
}
t.traceEnd(); // startCoreServices
}
6.3.3startOtherServices
// /frameworks/base/services/java/com/android/server/SystemServer.java
/**
* Starts a miscellaneous grab bag of stuff that has yet to be refactored and organized.
*/
private void startOtherServices(@NonNull TimingsTraceAndSlog t) {
t.traceBegin("startOtherServices");
mSystemServiceManager.updateOtherServicesStartIndex();
final Context context = mSystemContext;
DynamicSystemService dynamicSystem = null;
IStorageManager storageManager = null;
NetworkManagementService networkManagement = null;
VpnManagerService vpnManager = null;
VcnManagementService vcnManagement = null;
NetworkPolicyManagerService networkPolicy = null;
WindowManagerService wm = null;
SerialService serial = null;
NetworkTimeUpdateService networkTimeUpdater = null;
InputManagerService inputManager = null;
TelephonyRegistry telephonyRegistry = null;
ConsumerIrService consumerIr = null;
MmsServiceBroker mmsService = null;
HardwarePropertiesManagerService hardwarePropertiesService = null;
PacProxyService pacProxyService = null;
boolean disableSystemTextClassifier = SystemProperties.getBoolean(
"config.disable_systemtextclassifier", false);
boolean disableNetworkTime = SystemProperties.getBoolean("config.disable_networktime",
false);
boolean disableCameraService = SystemProperties.getBoolean("config.disable_cameraservice",
false);
boolean isEmulator = SystemProperties.get("ro.boot.qemu").equals("1");
boolean isWatch = context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_WATCH);
boolean isArc = context.getPackageManager().hasSystemFeature(
"org.chromium.arc");
boolean isTv = context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_LEANBACK);
boolean enableVrService = context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE);
// For debugging RescueParty
if (Build.IS_DEBUGGABLE && SystemProperties.getBoolean("debug.crash_system", false)) {
throw new RuntimeException();
}
try {
final String SECONDARY_ZYGOTE_PRELOAD = "SecondaryZygotePreload";
// We start the preload ~1s before the webview factory preparation, to
// ensure that it completes before the 32 bit relro process is forked
// from the zygote. In the event that it takes too long, the webview
// RELRO process will block, but it will do so without holding any locks.
mZygotePreload = SystemServerInitThreadPool.submit(() -> {
try {
Slog.i(TAG, SECONDARY_ZYGOTE_PRELOAD);
TimingsTraceAndSlog traceLog = TimingsTraceAndSlog.newAsyncLog();
traceLog.traceBegin(SECONDARY_ZYGOTE_PRELOAD);
String[] abis32 = Build.SUPPORTED_32_BIT_ABIS;
if (abis32.length > 0 && !Process.ZYGOTE_PROCESS.preloadDefault(abis32[0])) {
Slog.e(TAG, "Unable to preload default resources for secondary");
}
traceLog.traceEnd();
} catch (Exception ex) {
Slog.e(TAG, "Exception preloading default resources", ex);
}
}, SECONDARY_ZYGOTE_PRELOAD);
t.traceBegin("StartKeyAttestationApplicationIdProviderService");
ServiceManager.addService("sec_key_att_app_id_provider",
new KeyAttestationApplicationIdProviderService(context));
t.traceEnd();
t.traceBegin("StartKeyChainSystemService");
mSystemServiceManager.startService(KeyChainSystemService.class);
t.traceEnd();
t.traceBegin("StartBinaryTransparencyService");
mSystemServiceManager.startService(BinaryTransparencyService.class);
t.traceEnd();
t.traceBegin("StartSchedulingPolicyService");
ServiceManager.addService("scheduling_policy", new SchedulingPolicyService());
t.traceEnd();
// TelecomLoader hooks into classes with defined HFP logic,
// so check for either telephony or microphone.
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_MICROPHONE)
|| mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELECOM)
|| mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
//启动通话相关核心服务
t.traceBegin("StartTelecomLoaderService");
mSystemServiceManager.startService(TelecomLoaderService.class);
t.traceEnd();
}
t.traceBegin("StartTelephonyRegistry");
telephonyRegistry = new TelephonyRegistry(
context, new TelephonyRegistry.ConfigurationProvider());
ServiceManager.addService("telephony.registry", telephonyRegistry);
t.traceEnd();
t.traceBegin("StartEntropyMixer");
mEntropyMixer = new EntropyMixer(context);
t.traceEnd();
mContentResolver = context.getContentResolver();
// The AccountManager must come before the ContentService
// 启动 用户管理服务 ,必现在StartContentService 之前
t.traceBegin("StartAccountManagerService");
mSystemServiceManager.startService(ACCOUNT_SERVICE_CLASS);
t.traceEnd();
t.traceBegin("StartContentService");
mSystemServiceManager.startService(CONTENT_SERVICE_CLASS);
t.traceEnd();
t.traceBegin("InstallSystemProviders");
mActivityManagerService.getContentProviderHelper().installSystemProviders();
// Device configuration used to be part of System providers
mSystemServiceManager.startService(UPDATABLE_DEVICE_CONFIG_SERVICE_CLASS);
// Now that SettingsProvider is ready, reactivate SQLiteCompatibilityWalFlags
SQLiteCompatibilityWalFlags.reset();
t.traceEnd();
// Records errors and logs, for example wtf()
// Currently this service indirectly depends on SettingsProvider so do this after
// InstallSystemProviders.
t.traceBegin("StartDropBoxManager");
mSystemServiceManager.startService(DropBoxManagerService.class);
t.traceEnd();
// Grants default permissions and defines roles
t.traceBegin("StartRoleManagerService");
LocalManagerRegistry.addManager(RoleServicePlatformHelper.class,
new RoleServicePlatformHelperImpl(mSystemContext));
mSystemServiceManager.startService(ROLE_SERVICE_CLASS);
t.traceEnd();
t.traceBegin("StartVibratorManagerService");
mSystemServiceManager.startService(VibratorManagerService.Lifecycle.class);
t.traceEnd();
t.traceBegin("StartDynamicSystemService");
dynamicSystem = new DynamicSystemService(context);
ServiceManager.addService("dynamic_system", dynamicSystem);
t.traceEnd();
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CONSUMER_IR)) {
t.traceBegin("StartConsumerIrService");
consumerIr = new ConsumerIrService(context);
ServiceManager.addService(Context.CONSUMER_IR_SERVICE, consumerIr);
t.traceEnd();
}
// TODO(aml-jobscheduler): Think about how to do it properly.
t.traceBegin("StartResourceEconomy");
mSystemServiceManager.startService(RESOURCE_ECONOMY_SERVICE_CLASS);
t.traceEnd();
// TODO(aml-jobscheduler): Think about how to do it properly.
t.traceBegin("StartAlarmManagerService");
mSystemServiceManager.startService(ALARM_MANAGER_SERVICE_CLASS);
t.traceEnd();
t.traceBegin("StartInputManagerService");
inputManager = new InputManagerService(context);
t.traceEnd();
t.traceBegin("DeviceStateManagerService");
mSystemServiceManager.startService(DeviceStateManagerService.class);
t.traceEnd();
if (!disableCameraService) {
t.traceBegin("StartCameraServiceProxy");
mSystemServiceManager.startService(CameraServiceProxy.class);
t.traceEnd();
}
// 启动WMS
t.traceBegin("StartWindowManagerService");
// WMS needs sensor service ready
mSystemServiceManager.startBootPhase(t, SystemService.PHASE_WAIT_FOR_SENSOR_SERVICE);
wm = WindowManagerService.main(context, inputManager, !mFirstBoot,
new PhoneWindowManager(), mActivityManagerService.mActivityTaskManager);
ServiceManager.addService(Context.WINDOW_SERVICE, wm, /* allowIsolated= */ false,
DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PROTO);
ServiceManager.addService(Context.INPUT_SERVICE, inputManager,
/* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
t.traceEnd();
// 设置WindowManager
t.traceBegin("SetWindowManagerService");
mActivityManagerService.setWindowManager(wm);
t.traceEnd();
t.traceBegin("WindowManagerServiceOnInitReady");
wm.onInitReady();
t.traceEnd();
// Start receiving calls from SensorManager services. Start in a separate thread
// because it need to connect to SensorManager. This has to start
// after PHASE_WAIT_FOR_SENSOR_SERVICE is done.
SystemServerInitThreadPool.submit(() -> {
TimingsTraceAndSlog traceLog = TimingsTraceAndSlog.newAsyncLog();
traceLog.traceBegin(START_SENSOR_MANAGER_SERVICE);
startISensorManagerService();
traceLog.traceEnd();
}, START_SENSOR_MANAGER_SERVICE);
SystemServerInitThreadPool.submit(() -> {
TimingsTraceAndSlog traceLog = TimingsTraceAndSlog.newAsyncLog();
traceLog.traceBegin(START_HIDL_SERVICES);
startHidlServices();
traceLog.traceEnd();
}, START_HIDL_SERVICES);
if (!isWatch && enableVrService) {
t.traceBegin("StartVrManagerService");
mSystemServiceManager.startService(VrManagerService.class);
t.traceEnd();
}
t.traceBegin("StartInputManager");
inputManager.setWindowManagerCallbacks(wm.getInputManagerCallback());
inputManager.start();
t.traceEnd();
// TODO: Use service dependencies instead.
t.traceBegin("DisplayManagerWindowManagerAndInputReady");
mDisplayManagerService.windowManagerAndInputReady();
t.traceEnd();
if (mFactoryTestMode == FactoryTest.FACTORY_TEST_LOW_LEVEL) {
Slog.i(TAG, "No Bluetooth Service (factory test)");
} else if (!context.getPackageManager().hasSystemFeature
(PackageManager.FEATURE_BLUETOOTH)) {
Slog.i(TAG, "No Bluetooth Service (Bluetooth Hardware Not Present)");
} else {
t.traceBegin("StartBluetoothService");
mSystemServiceManager.startServiceFromJar(BLUETOOTH_SERVICE_CLASS,
BLUETOOTH_APEX_SERVICE_JAR_PATH);
t.traceEnd();
}
t.traceBegin("IpConnectivityMetrics");
mSystemServiceManager.startService(IP_CONNECTIVITY_METRICS_CLASS);
t.traceEnd();
t.traceBegin("NetworkWatchlistService");
mSystemServiceManager.startService(NetworkWatchlistService.Lifecycle.class);
t.traceEnd();
t.traceBegin("PinnerService");
mSystemServiceManager.startService(PinnerService.class);
t.traceEnd();
if (Build.IS_DEBUGGABLE && ProfcollectForwardingService.enabled()) {
t.traceBegin("ProfcollectForwardingService");
mSystemServiceManager.startService(ProfcollectForwardingService.class);
t.traceEnd();
}
t.traceBegin("SignedConfigService");
SignedConfigService.registerUpdateReceiver(mSystemContext);
t.traceEnd();
t.traceBegin("AppIntegrityService");
mSystemServiceManager.startService(AppIntegrityManagerService.class);
t.traceEnd();
t.traceBegin("StartLogcatManager");
mSystemServiceManager.startService(LogcatManagerService.class);
t.traceEnd();
} catch (Throwable e) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting core service");
throw e;
}
// Before things start rolling, be sure we have decided whether
// we are in safe mode.
final boolean safeMode = wm.detectSafeMode();
if (safeMode) {
// If yes, immediately turn on the global setting for airplane mode.
// Note that this does not send broadcasts at this stage because
// subsystems are not yet up. We will send broadcasts later to ensure
// all listeners have the chance to react with special handling.
Settings.Global.putInt(context.getContentResolver(),
Settings.Global.AIRPLANE_MODE_ON, 1);
} else if (context.getResources().getBoolean(R.bool.config_autoResetAirplaneMode)) {
Settings.Global.putInt(context.getContentResolver(),
Settings.Global.AIRPLANE_MODE_ON, 0);
}
StatusBarManagerService statusBar = null;
INotificationManager notification = null;
CountryDetectorService countryDetector = null;
ILockSettings lockSettings = null;
MediaRouterService mediaRouter = null;
// Bring up services needed for UI.
if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
t.traceBegin("StartInputMethodManagerLifecycle");
String immsClassName = context.getResources().getString(
R.string.config_deviceSpecificInputMethodManagerService);
if (immsClassName.isEmpty()) {
mSystemServiceManager.startService(InputMethodManagerService.Lifecycle.class);
} else {
try {
Slog.i(TAG, "Starting custom IMMS: " + immsClassName);
mSystemServiceManager.startService(immsClassName);
} catch (Throwable e) {
reportWtf("starting " + immsClassName, e);
}
}
t.traceEnd();
t.traceBegin("StartAccessibilityManagerService");
try {
mSystemServiceManager.startService(ACCESSIBILITY_MANAGER_SERVICE_CLASS);
} catch (Throwable e) {
reportWtf("starting Accessibility Manager", e);
}
t.traceEnd();
}
t.traceBegin("MakeDisplayReady");
try {
wm.displayReady();
} catch (Throwable e) {
reportWtf("making display ready", e);
}
t.traceEnd();
if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
if (!"0".equals(SystemProperties.get("system_init.startmountservice"))) {
t.traceBegin("StartStorageManagerService");
try {
/*
* NotificationManagerService is dependant on StorageManagerService,
* (for media / usb notifications) so we must start StorageManagerService first.
*/
mSystemServiceManager.startService(STORAGE_MANAGER_SERVICE_CLASS);
storageManager = IStorageManager.Stub.asInterface(
ServiceManager.getService("mount"));
} catch (Throwable e) {
reportWtf("starting StorageManagerService", e);
}
t.traceEnd();
t.traceBegin("StartStorageStatsService");
try {
mSystemServiceManager.startService(STORAGE_STATS_SERVICE_CLASS);
} catch (Throwable e) {
reportWtf("starting StorageStatsService", e);
}
t.traceEnd();
}
}
// We start this here so that we update our configuration to set watch or television
// as appropriate.
t.traceBegin("StartUiModeManager");
mSystemServiceManager.startService(UiModeManagerService.class);
t.traceEnd();
t.traceBegin("StartLocaleManagerService");
try {
mSystemServiceManager.startService(LocaleManagerService.class);
} catch (Throwable e) {
reportWtf("starting LocaleManagerService service", e);
}
t.traceEnd();
t.traceBegin("StartGrammarInflectionService");
try {
mSystemServiceManager.startService(GrammaticalInflectionService.class);
} catch (Throwable e) {
reportWtf("starting GrammarInflectionService service", e);
}
t.traceEnd();
t.traceBegin("StartAppHibernationService");
mSystemServiceManager.startService(APP_HIBERNATION_SERVICE_CLASS);
t.traceEnd();
t.traceBegin("ArtManagerLocal");
DexOptHelper.initializeArtManagerLocal(context, mPackageManagerService);
t.traceEnd();
t.traceBegin("UpdatePackagesIfNeeded");
try {
Watchdog.getInstance().pauseWatchingCurrentThread("dexopt");
mPackageManagerService.updatePackagesIfNeeded();
} catch (Throwable e) {
reportWtf("update packages", e);
} finally {
Watchdog.getInstance().resumeWatchingCurrentThread("dexopt");
}
t.traceEnd();
t.traceBegin("PerformFstrimIfNeeded");
try {
mPackageManagerService.performFstrimIfNeeded();
} catch (Throwable e) {
reportWtf("performing fstrim", e);
}
t.traceEnd();
final DevicePolicyManagerService.Lifecycle dpms;
if (mFactoryTestMode == FactoryTest.FACTORY_TEST_LOW_LEVEL) {
dpms = null;
} else {
t.traceBegin("StartLockSettingsService");
try {
mSystemServiceManager.startService(LOCK_SETTINGS_SERVICE_CLASS);
lockSettings = ILockSettings.Stub.asInterface(
ServiceManager.getService("lock_settings"));
} catch (Throwable e) {
reportWtf("starting LockSettingsService service", e);
}
t.traceEnd();
final boolean hasPdb = !SystemProperties.get(PERSISTENT_DATA_BLOCK_PROP).equals("");
if (hasPdb) {
t.traceBegin("StartPersistentDataBlock");
mSystemServiceManager.startService(PersistentDataBlockService.class);
t.traceEnd();
}
t.traceBegin("StartTestHarnessMode");
mSystemServiceManager.startService(TestHarnessModeService.class);
t.traceEnd();
if (hasPdb || OemLockService.isHalPresent()) {
// Implementation depends on pdb or the OemLock HAL
t.traceBegin("StartOemLockService");
mSystemServiceManager.startService(OemLockService.class);
t.traceEnd();
}
t.traceBegin("StartDeviceIdleController");
mSystemServiceManager.startService(DEVICE_IDLE_CONTROLLER_CLASS);
t.traceEnd();
// Always start the Device Policy Manager, so that the API is compatible with
// API8.
t.traceBegin("StartDevicePolicyManager");
dpms = mSystemServiceManager.startService(DevicePolicyManagerService.Lifecycle.class);
t.traceEnd();
t.traceBegin("StartStatusBarManagerService");
try {
statusBar = new StatusBarManagerService(context);
if (!isWatch) {
statusBar.publishGlobalActionsProvider();
}
ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar, false,
DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
} catch (Throwable e) {
reportWtf("starting StatusBarManagerService", e);
}
t.traceEnd();
if (deviceHasConfigString(context,
R.string.config_defaultMusicRecognitionService)) {
t.traceBegin("StartMusicRecognitionManagerService");
mSystemServiceManager.startService(MUSIC_RECOGNITION_MANAGER_SERVICE_CLASS);
t.traceEnd();
} else {
Slog.d(TAG,
"MusicRecognitionManagerService not defined by OEM or disabled by flag");
}
startContentCaptureService(context, t);
startAttentionService(context, t);
startRotationResolverService(context, t);
startSystemCaptionsManagerService(context, t);
startTextToSpeechManagerService(context, t);
startAmbientContextService(t);
startWearableSensingService(t);
// System Speech Recognition Service
t.traceBegin("StartSpeechRecognitionManagerService");
mSystemServiceManager.startService(SPEECH_RECOGNITION_MANAGER_SERVICE_CLASS);
t.traceEnd();
// App prediction manager service
if (deviceHasConfigString(context, R.string.config_defaultAppPredictionService)) {
t.traceBegin("StartAppPredictionService");
mSystemServiceManager.startService(APP_PREDICTION_MANAGER_SERVICE_CLASS);
t.traceEnd();
} else {
Slog.d(TAG, "AppPredictionService not defined by OEM");
}
// Content suggestions manager service
if (deviceHasConfigString(context, R.string.config_defaultContentSuggestionsService)) {
t.traceBegin("StartContentSuggestionsService");
mSystemServiceManager.startService(CONTENT_SUGGESTIONS_SERVICE_CLASS);
t.traceEnd();
} else {
Slog.d(TAG, "ContentSuggestionsService not defined by OEM");
}
// Search UI manager service
// TODO: add deviceHasConfigString(context, R.string.config_defaultSearchUiService)
t.traceBegin("StartSearchUiService");
mSystemServiceManager.startService(SEARCH_UI_MANAGER_SERVICE_CLASS);
t.traceEnd();
// Smartspace manager service
// TODO: add deviceHasConfigString(context, R.string.config_defaultSmartspaceService)
t.traceBegin("StartSmartspaceService");
mSystemServiceManager.startService(SMARTSPACE_MANAGER_SERVICE_CLASS);
t.traceEnd();
t.traceBegin("InitConnectivityModuleConnector");
try {
ConnectivityModuleConnector.getInstance().init(context);
} catch (Throwable e) {
reportWtf("initializing ConnectivityModuleConnector", e);
}
t.traceEnd();
t.traceBegin("InitNetworkStackClient");
try {
NetworkStackClient.getInstance().init();
} catch (Throwable e) {
reportWtf("initializing NetworkStackClient", e);
}
t.traceEnd();
t.traceBegin("StartNetworkManagementService");
try {
networkManagement = NetworkManagementService.create(context);
ServiceManager.addService(Context.NETWORKMANAGEMENT_SERVICE, networkManagement);
} catch (Throwable e) {
reportWtf("starting NetworkManagement Service", e);
}
t.traceEnd();
t.traceBegin("StartFontManagerService");
mSystemServiceManager.startService(new FontManagerService.Lifecycle(context, safeMode));
t.traceEnd();
t.traceBegin("StartTextServicesManager");
mSystemServiceManager.startService(TextServicesManagerService.Lifecycle.class);
t.traceEnd();
if (!disableSystemTextClassifier) {
t.traceBegin("StartTextClassificationManagerService");
mSystemServiceManager
.startService(TextClassificationManagerService.Lifecycle.class);
t.traceEnd();
}
t.traceBegin("StartNetworkScoreService");
mSystemServiceManager.startService(NetworkScoreService.Lifecycle.class);
t.traceEnd();
t.traceBegin("StartNetworkStatsService");
// This has to be called before NetworkPolicyManager because NetworkPolicyManager
// needs to take NetworkStatsService to initialize.
mSystemServiceManager.startServiceFromJar(NETWORK_STATS_SERVICE_INITIALIZER_CLASS,
CONNECTIVITY_SERVICE_APEX_PATH);
t.traceEnd();
t.traceBegin("StartNetworkPolicyManagerService");
try {
networkPolicy = new NetworkPolicyManagerService(context, mActivityManagerService,
networkManagement);
ServiceManager.addService(Context.NETWORK_POLICY_SERVICE, networkPolicy);
} catch (Throwable e) {
reportWtf("starting NetworkPolicy Service", e);
}
t.traceEnd();
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_WIFI)) {
// Wifi Service must be started first for wifi-related services.
t.traceBegin("StartWifi");
mSystemServiceManager.startServiceFromJar(
WIFI_SERVICE_CLASS, WIFI_APEX_SERVICE_JAR_PATH);
t.traceEnd();
t.traceBegin("StartWifiScanning");
mSystemServiceManager.startServiceFromJar(
WIFI_SCANNING_SERVICE_CLASS, WIFI_APEX_SERVICE_JAR_PATH);
t.traceEnd();
}
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_WIFI_RTT)) {
t.traceBegin("StartRttService");
mSystemServiceManager.startServiceFromJar(
WIFI_RTT_SERVICE_CLASS, WIFI_APEX_SERVICE_JAR_PATH);
t.traceEnd();
}
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_WIFI_AWARE)) {
t.traceBegin("StartWifiAware");
mSystemServiceManager.startServiceFromJar(
WIFI_AWARE_SERVICE_CLASS, WIFI_APEX_SERVICE_JAR_PATH);
t.traceEnd();
}
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_WIFI_DIRECT)) {
t.traceBegin("StartWifiP2P");
mSystemServiceManager.startServiceFromJar(
WIFI_P2P_SERVICE_CLASS, WIFI_APEX_SERVICE_JAR_PATH);
t.traceEnd();
}
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_LOWPAN)) {
t.traceBegin("StartLowpan");
mSystemServiceManager.startService(LOWPAN_SERVICE_CLASS);
t.traceEnd();
}
t.traceBegin("StartPacProxyService");
try {
pacProxyService = new PacProxyService(context);
ServiceManager.addService(Context.PAC_PROXY_SERVICE, pacProxyService);
} catch (Throwable e) {
reportWtf("starting PacProxyService", e);
}
t.traceEnd();
t.traceBegin("StartConnectivityService");
// This has to be called after NetworkManagementService, NetworkStatsService
// and NetworkPolicyManager because ConnectivityService needs to take these
// services to initialize.
mSystemServiceManager.startServiceFromJar(CONNECTIVITY_SERVICE_INITIALIZER_CLASS,
CONNECTIVITY_SERVICE_APEX_PATH);
networkPolicy.bindConnectivityManager();
t.traceEnd();
t.traceBegin("StartVpnManagerService");
try {
vpnManager = VpnManagerService.create(context);
ServiceManager.addService(Context.VPN_MANAGEMENT_SERVICE, vpnManager);
} catch (Throwable e) {
reportWtf("starting VPN Manager Service", e);
}
t.traceEnd();
t.traceBegin("StartVcnManagementService");
try {
vcnManagement = VcnManagementService.create(context);
ServiceManager.addService(Context.VCN_MANAGEMENT_SERVICE, vcnManagement);
} catch (Throwable e) {
reportWtf("starting VCN Management Service", e);
}
t.traceEnd();
t.traceBegin("StartSystemUpdateManagerService");
try {
ServiceManager.addService(Context.SYSTEM_UPDATE_SERVICE,
new SystemUpdateManagerService(context));
} catch (Throwable e) {
reportWtf("starting SystemUpdateManagerService", e);
}
t.traceEnd();
t.traceBegin("StartUpdateLockService");
try {
ServiceManager.addService(Context.UPDATE_LOCK_SERVICE,
new UpdateLockService(context));
} catch (Throwable e) {
reportWtf("starting UpdateLockService", e);
}
t.traceEnd();
t.traceBegin("StartNotificationManager");
mSystemServiceManager.startService(NotificationManagerService.class);
SystemNotificationChannels.removeDeprecated(context);
SystemNotificationChannels.createAll(context);
notification = INotificationManager.Stub.asInterface(
ServiceManager.getService(Context.NOTIFICATION_SERVICE));
t.traceEnd();
t.traceBegin("StartDeviceMonitor");
mSystemServiceManager.startService(DeviceStorageMonitorService.class);
t.traceEnd();
t.traceBegin("StartTimeDetectorService");
try {
mSystemServiceManager.startService(TIME_DETECTOR_SERVICE_CLASS);
} catch (Throwable e) {
reportWtf("starting TimeDetectorService service", e);
}
t.traceEnd();
t.traceBegin("StartLocationManagerService");
mSystemServiceManager.startService(LocationManagerService.Lifecycle.class);
t.traceEnd();
t.traceBegin("StartCountryDetectorService");
try {
countryDetector = new CountryDetectorService(context);
ServiceManager.addService(Context.COUNTRY_DETECTOR, countryDetector);
} catch (Throwable e) {
reportWtf("starting Country Detector", e);
}
t.traceEnd();
t.traceBegin("StartTimeZoneDetectorService");
try {
mSystemServiceManager.startService(TIME_ZONE_DETECTOR_SERVICE_CLASS);
} catch (Throwable e) {
reportWtf("starting TimeZoneDetectorService service", e);
}
t.traceEnd();
t.traceBegin("StartAltitudeService");
try {
mSystemServiceManager.startService(AltitudeService.Lifecycle.class);
} catch (Throwable e) {
reportWtf("starting AltitudeService service", e);
}
t.traceEnd();
t.traceBegin("StartLocationTimeZoneManagerService");
try {
mSystemServiceManager.startService(LOCATION_TIME_ZONE_MANAGER_SERVICE_CLASS);
} catch (Throwable e) {
reportWtf("starting LocationTimeZoneManagerService service", e);
}
t.traceEnd();
if (context.getResources().getBoolean(R.bool.config_enableGnssTimeUpdateService)) {
t.traceBegin("StartGnssTimeUpdateService");
try {
mSystemServiceManager.startService(GNSS_TIME_UPDATE_SERVICE_CLASS);
} catch (Throwable e) {
reportWtf("starting GnssTimeUpdateService service", e);
}
t.traceEnd();
}
if (!isWatch) {
t.traceBegin("StartSearchManagerService");
try {
mSystemServiceManager.startService(SEARCH_MANAGER_SERVICE_CLASS);
} catch (Throwable e) {
reportWtf("starting Search Service", e);
}
t.traceEnd();
}
if (context.getResources().getBoolean(R.bool.config_enableWallpaperService)) {
t.traceBegin("StartWallpaperManagerService");
mSystemServiceManager.startService(WALLPAPER_SERVICE_CLASS);
t.traceEnd();
} else {
Slog.i(TAG, "Wallpaper service disabled by config");
}
// WallpaperEffectsGeneration manager service
// TODO (b/135218095): Use deviceHasConfigString(context,
// R.string.config_defaultWallpaperEffectsGenerationService)
t.traceBegin("StartWallpaperEffectsGenerationService");
mSystemServiceManager.startService(
WALLPAPER_EFFECTS_GENERATION_MANAGER_SERVICE_CLASS);
t.traceEnd();
t.traceBegin("StartAudioService");
if (!isArc) {
mSystemServiceManager.startService(AudioService.Lifecycle.class);
} else {
String className = context.getResources()
.getString(R.string.config_deviceSpecificAudioService);
try {
mSystemServiceManager.startService(className + "$Lifecycle");
} catch (Throwable e) {
reportWtf("starting " + className, e);
}
}
t.traceEnd();
t.traceBegin("StartSoundTriggerMiddlewareService");
mSystemServiceManager.startService(SoundTriggerMiddlewareService.Lifecycle.class);
t.traceEnd();
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_BROADCAST_RADIO)) {
t.traceBegin("StartBroadcastRadioService");
mSystemServiceManager.startService(BroadcastRadioService.class);
t.traceEnd();
}
if (!isTv) {
t.traceBegin("StartDockObserver");
mSystemServiceManager.startService(DockObserver.class);
t.traceEnd();
}
if (isWatch) {
t.traceBegin("StartThermalObserver");
mSystemServiceManager.startService(THERMAL_OBSERVER_CLASS);
t.traceEnd();
}
if (!isWatch) {
t.traceBegin("StartWiredAccessoryManager");
try {
// Listen for wired headset changes
inputManager.setWiredAccessoryCallbacks(
new WiredAccessoryManager(context, inputManager));
} catch (Throwable e) {
reportWtf("starting WiredAccessoryManager", e);
}
t.traceEnd();
}
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_MIDI)) {
// Start MIDI Manager service
t.traceBegin("StartMidiManager");
mSystemServiceManager.startService(MIDI_SERVICE_CLASS);
t.traceEnd();
}
// Start ADB Debugging Service
t.traceBegin("StartAdbService");
try {
mSystemServiceManager.startService(ADB_SERVICE_CLASS);
} catch (Throwable e) {
Slog.e(TAG, "Failure starting AdbService");
}
t.traceEnd();
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_HOST)
|| mPackageManager.hasSystemFeature(
PackageManager.FEATURE_USB_ACCESSORY)
|| isEmulator) {
// Manage USB host and device support
t.traceBegin("StartUsbService");
mSystemServiceManager.startService(USB_SERVICE_CLASS);
t.traceEnd();
}
if (!isWatch) {
t.traceBegin("StartSerialService");
try {
// Serial port support
serial = new SerialService(context);
ServiceManager.addService(Context.SERIAL_SERVICE, serial);
} catch (Throwable e) {
Slog.e(TAG, "Failure starting SerialService", e);
}
t.traceEnd();
}
t.traceBegin("StartHardwarePropertiesManagerService");
try {
hardwarePropertiesService = new HardwarePropertiesManagerService(context);
ServiceManager.addService(Context.HARDWARE_PROPERTIES_SERVICE,
hardwarePropertiesService);
} catch (Throwable e) {
Slog.e(TAG, "Failure starting HardwarePropertiesManagerService", e);
}
t.traceEnd();
if (!isWatch) {
t.traceBegin("StartTwilightService");
mSystemServiceManager.startService(TwilightService.class);
t.traceEnd();
}
t.traceBegin("StartColorDisplay");
mSystemServiceManager.startService(ColorDisplayService.class);
t.traceEnd();
// TODO(aml-jobscheduler): Think about how to do it properly.
t.traceBegin("StartJobScheduler");
mSystemServiceManager.startService(JOB_SCHEDULER_SERVICE_CLASS);
t.traceEnd();
t.traceBegin("StartSoundTrigger");
mSystemServiceManager.startService(SoundTriggerService.class);
t.traceEnd();
t.traceBegin("StartTrustManager");
mSystemServiceManager.startService(TrustManagerService.class);
t.traceEnd();
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_BACKUP)) {
t.traceBegin("StartBackupManager");
mSystemServiceManager.startService(BACKUP_MANAGER_SERVICE_CLASS);
t.traceEnd();
}
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_APP_WIDGETS)
|| context.getResources().getBoolean(R.bool.config_enableAppWidgetService)) {
t.traceBegin("StartAppWidgetService");
mSystemServiceManager.startService(APPWIDGET_SERVICE_CLASS);
t.traceEnd();
}
// We need to always start this service, regardless of whether the
// FEATURE_VOICE_RECOGNIZERS feature is set, because it needs to take care
// of initializing various settings. It will internally modify its behavior
// based on that feature.
t.traceBegin("StartVoiceRecognitionManager");
mSystemServiceManager.startService(VOICE_RECOGNITION_MANAGER_SERVICE_CLASS);
t.traceEnd();
if (GestureLauncherService.isGestureLauncherEnabled(context.getResources())) {
t.traceBegin("StartGestureLauncher");
mSystemServiceManager.startService(GestureLauncherService.class);
t.traceEnd();
}
t.traceBegin("StartSensorNotification");
mSystemServiceManager.startService(SensorNotificationService.class);
t.traceEnd();
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_CONTEXT_HUB)) {
t.traceBegin("StartContextHubSystemService");
mSystemServiceManager.startService(ContextHubSystemService.class);
t.traceEnd();
}
t.traceBegin("StartDiskStatsService");
try {
ServiceManager.addService("diskstats", new DiskStatsService(context));
} catch (Throwable e) {
reportWtf("starting DiskStats Service", e);
}
t.traceEnd();
t.traceBegin("RuntimeService");
try {
ServiceManager.addService("runtime", new RuntimeService(context));
} catch (Throwable e) {
reportWtf("starting RuntimeService", e);
}
t.traceEnd();
if (!isWatch && !disableNetworkTime) {
t.traceBegin("StartNetworkTimeUpdateService");
try {
networkTimeUpdater = new NetworkTimeUpdateService(context);
ServiceManager.addService("network_time_update_service", networkTimeUpdater);
} catch (Throwable e) {
reportWtf("starting NetworkTimeUpdate service", e);
}
t.traceEnd();
}
t.traceBegin("CertBlacklister");
try {
CertBlacklister blacklister = new CertBlacklister(context);
} catch (Throwable e) {
reportWtf("starting CertBlacklister", e);
}
t.traceEnd();
if (EmergencyAffordanceManager.ENABLED) {
// EmergencyMode service
t.traceBegin("StartEmergencyAffordanceService");
mSystemServiceManager.startService(EmergencyAffordanceService.class);
t.traceEnd();
}
t.traceBegin(START_BLOB_STORE_SERVICE);
mSystemServiceManager.startService(BLOB_STORE_MANAGER_SERVICE_CLASS);
t.traceEnd();
// Dreams (interactive idle-time views, a/k/a screen savers, and doze mode)
t.traceBegin("StartDreamManager");
mSystemServiceManager.startService(DreamManagerService.class);
t.traceEnd();
t.traceBegin("AddGraphicsStatsService");
ServiceManager.addService(GraphicsStatsService.GRAPHICS_STATS_SERVICE,
new GraphicsStatsService(context));
t.traceEnd();
if (CoverageService.ENABLED) {
t.traceBegin("AddCoverageService");
ServiceManager.addService(CoverageService.COVERAGE_SERVICE, new CoverageService());
t.traceEnd();
}
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_PRINTING)) {
t.traceBegin("StartPrintManager");
mSystemServiceManager.startService(PRINT_MANAGER_SERVICE_CLASS);
t.traceEnd();
}
t.traceBegin("StartAttestationVerificationService");
mSystemServiceManager.startService(AttestationVerificationManagerService.class);
t.traceEnd();
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_COMPANION_DEVICE_SETUP)) {
t.traceBegin("StartCompanionDeviceManager");
mSystemServiceManager.startService(COMPANION_DEVICE_MANAGER_SERVICE_CLASS);
t.traceEnd();
// VirtualDeviceManager depends on CDM to control the associations.
t.traceBegin("StartVirtualDeviceManager");
mSystemServiceManager.startService(VIRTUAL_DEVICE_MANAGER_SERVICE_CLASS);
t.traceEnd();
}
t.traceBegin("StartRestrictionManager");
mSystemServiceManager.startService(RestrictionsManagerService.class);
t.traceEnd();
t.traceBegin("StartMediaSessionService");
mSystemServiceManager.startService(MEDIA_SESSION_SERVICE_CLASS);
t.traceEnd();
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_HDMI_CEC)) {
t.traceBegin("StartHdmiControlService");
mSystemServiceManager.startService(HdmiControlService.class);
t.traceEnd();
}
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_LIVE_TV)
|| mPackageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)) {
t.traceBegin("StartTvInteractiveAppManager");
mSystemServiceManager.startService(TvInteractiveAppManagerService.class);
t.traceEnd();
}
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_LIVE_TV)
|| mPackageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)) {
t.traceBegin("StartTvInputManager");
mSystemServiceManager.startService(TvInputManagerService.class);
t.traceEnd();
}
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_TUNER)) {
t.traceBegin("StartTunerResourceManager");
mSystemServiceManager.startService(TunerResourceManagerService.class);
t.traceEnd();
}
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)) {
t.traceBegin("StartMediaResourceMonitor");
mSystemServiceManager.startService(MEDIA_RESOURCE_MONITOR_SERVICE_CLASS);
t.traceEnd();
}
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)) {
t.traceBegin("StartTvRemoteService");
mSystemServiceManager.startService(TvRemoteService.class);
t.traceEnd();
}
t.traceBegin("StartMediaRouterService");
try {
mediaRouter = new MediaRouterService(context);
ServiceManager.addService(Context.MEDIA_ROUTER_SERVICE, mediaRouter);
} catch (Throwable e) {
reportWtf("starting MediaRouterService", e);
}
t.traceEnd();
final boolean hasFeatureFace
= mPackageManager.hasSystemFeature(PackageManager.FEATURE_FACE);
final boolean hasFeatureIris
= mPackageManager.hasSystemFeature(PackageManager.FEATURE_IRIS);
final boolean hasFeatureFingerprint
= mPackageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT);
if (hasFeatureFace) {
t.traceBegin("StartFaceSensor");
final FaceService faceService =
mSystemServiceManager.startService(FaceService.class);
t.traceEnd();
}
if (hasFeatureIris) {
t.traceBegin("StartIrisSensor");
mSystemServiceManager.startService(IrisService.class);
t.traceEnd();
}
if (hasFeatureFingerprint) {
t.traceBegin("StartFingerprintSensor");
final FingerprintService fingerprintService =
mSystemServiceManager.startService(FingerprintService.class);
t.traceEnd();
}
// Start this service after all biometric sensor services are started.
t.traceBegin("StartBiometricService");
mSystemServiceManager.startService(BiometricService.class);
t.traceEnd();
t.traceBegin("StartAuthService");
mSystemServiceManager.startService(AuthService.class);
t.traceEnd();
if (!isWatch) {
// We don't run this on watches as there are no plans to use the data logged
// on watch devices.
t.traceBegin("StartDynamicCodeLoggingService");
try {
DynamicCodeLoggingService.schedule(context);
} catch (Throwable e) {
reportWtf("starting DynamicCodeLoggingService", e);
}
t.traceEnd();
}
if (!isWatch) {
t.traceBegin("StartPruneInstantAppsJobService");
try {
PruneInstantAppsJobService.schedule(context);
} catch (Throwable e) {
reportWtf("StartPruneInstantAppsJobService", e);
}
t.traceEnd();
}
// LauncherAppsService uses ShortcutService.
t.traceBegin("StartShortcutServiceLifecycle");
mSystemServiceManager.startService(ShortcutService.Lifecycle.class);
t.traceEnd();
t.traceBegin("StartLauncherAppsService");
mSystemServiceManager.startService(LauncherAppsService.class);
t.traceEnd();
t.traceBegin("StartCrossProfileAppsService");
mSystemServiceManager.startService(CrossProfileAppsService.class);
t.traceEnd();
t.traceBegin("StartPeopleService");
mSystemServiceManager.startService(PeopleService.class);
t.traceEnd();
t.traceBegin("StartMediaMetricsManager");
mSystemServiceManager.startService(MediaMetricsManagerService.class);
t.traceEnd();
t.traceBegin("StartBackgroundInstallControlService");
mSystemServiceManager.startService(BackgroundInstallControlService.class);
t.traceEnd();
}
t.traceBegin("StartMediaProjectionManager");
mSystemServiceManager.startService(MediaProjectionManagerService.class);
t.traceEnd();
if (isWatch) {
// Must be started before services that depend it, e.g. WearConnectivityService
t.traceBegin("StartWearPowerService");
mSystemServiceManager.startService(WEAR_POWER_SERVICE_CLASS);
t.traceEnd();
t.traceBegin("StartHealthService");
mSystemServiceManager.startService(HEALTH_SERVICE_CLASS);
t.traceEnd();
t.traceBegin("StartWearConnectivityService");
mSystemServiceManager.startService(WEAR_CONNECTIVITY_SERVICE_CLASS);
t.traceEnd();
t.traceBegin("StartWearDisplayService");
mSystemServiceManager.startService(WEAR_DISPLAY_SERVICE_CLASS);
t.traceEnd();
t.traceBegin("StartWearTimeService");
mSystemServiceManager.startService(WEAR_TIME_SERVICE_CLASS);
t.traceEnd();
t.traceBegin("StartWearGlobalActionsService");
mSystemServiceManager.startService(WEAR_GLOBAL_ACTIONS_SERVICE_CLASS);
t.traceEnd();
}
if (!mPackageManager.hasSystemFeature(PackageManager.FEATURE_SLICES_DISABLED)) {
t.traceBegin("StartSliceManagerService");
mSystemServiceManager.startService(SLICE_MANAGER_SERVICE_CLASS);
t.traceEnd();
}
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_EMBEDDED)) {
t.traceBegin("StartIoTSystemService");
mSystemServiceManager.startService(IOT_SERVICE_CLASS);
t.traceEnd();
}
// Statsd helper
t.traceBegin("StartStatsCompanion");
mSystemServiceManager.startServiceFromJar(
STATS_COMPANION_LIFECYCLE_CLASS, STATS_COMPANION_APEX_PATH);
t.traceEnd();
// Reboot Readiness
t.traceBegin("StartRebootReadinessManagerService");
mSystemServiceManager.startServiceFromJar(
REBOOT_READINESS_LIFECYCLE_CLASS, SCHEDULING_APEX_PATH);
t.traceEnd();
// Statsd pulled atoms
t.traceBegin("StartStatsPullAtomService");
mSystemServiceManager.startService(STATS_PULL_ATOM_SERVICE_CLASS);
t.traceEnd();
// Log atoms to statsd from bootstrap processes.
t.traceBegin("StatsBootstrapAtomService");
mSystemServiceManager.startService(STATS_BOOTSTRAP_ATOM_SERVICE_LIFECYCLE_CLASS);
t.traceEnd();
// Incidentd and dumpstated helper
t.traceBegin("StartIncidentCompanionService");
mSystemServiceManager.startService(IncidentCompanionService.class);
t.traceEnd();
// SdkSandboxManagerService
t.traceBegin("StarSdkSandboxManagerService");
mSystemServiceManager.startService(SDK_SANDBOX_MANAGER_SERVICE_CLASS);
t.traceEnd();
// AdServicesManagerService (PP API service)
t.traceBegin("StartAdServicesManagerService");
SystemService adServices = mSystemServiceManager
.startService(AD_SERVICES_MANAGER_SERVICE_CLASS);
if (adServices instanceof Dumpable) {
mDumper.addDumpable((Dumpable) adServices);
}
t.traceEnd();
// OnDevicePersonalizationSystemService
t.traceBegin("StartOnDevicePersonalizationSystemService");
mSystemServiceManager.startService(ON_DEVICE_PERSONALIZATION_SYSTEM_SERVICE_CLASS);
t.traceEnd();
if (safeMode) {
mActivityManagerService.enterSafeMode();
}
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
// MMS service broker
t.traceBegin("StartMmsService");
mmsService = mSystemServiceManager.startService(MmsServiceBroker.class);
t.traceEnd();
}
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOFILL)) {
t.traceBegin("StartAutoFillService");
mSystemServiceManager.startService(AUTO_FILL_MANAGER_SERVICE_CLASS);
t.traceEnd();
}
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_CREDENTIALS)) {
boolean credentialManagerEnabled =
DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_CREDENTIAL,
CredentialManager.DEVICE_CONFIG_ENABLE_CREDENTIAL_MANAGER, true);
if (credentialManagerEnabled) {
t.traceBegin("StartCredentialManagerService");
mSystemServiceManager.startService(CREDENTIAL_MANAGER_SERVICE_CLASS);
t.traceEnd();
} else {
Slog.d(TAG, "CredentialManager disabled.");
}
}
// Translation manager service
if (deviceHasConfigString(context, R.string.config_defaultTranslationService)) {
t.traceBegin("StartTranslationManagerService");
mSystemServiceManager.startService(TRANSLATION_MANAGER_SERVICE_CLASS);
t.traceEnd();
} else {
Slog.d(TAG, "TranslationService not defined by OEM");
}
// Selection toolbar service
t.traceBegin("StartSelectionToolbarManagerService");
mSystemServiceManager.startService(SELECTION_TOOLBAR_MANAGER_SERVICE_CLASS);
t.traceEnd();
// NOTE: ClipboardService depends on ContentCapture and Autofill
t.traceBegin("StartClipboardService");
mSystemServiceManager.startService(ClipboardService.class);
t.traceEnd();
t.traceBegin("AppServiceManager");
mSystemServiceManager.startService(AppBindingService.Lifecycle.class);
t.traceEnd();
// Perfetto TracingServiceProxy
t.traceBegin("startTracingServiceProxy");
mSystemServiceManager.startService(TracingServiceProxy.class);
t.traceEnd();
// It is now time to start up the app processes...
t.traceBegin("MakeLockSettingsServiceReady");
if (lockSettings != null) {
try {
lockSettings.systemReady();
} catch (Throwable e) {
reportWtf("making Lock Settings Service ready", e);
}
}
t.traceEnd();
// Needed by DevicePolicyManager for initialization
t.traceBegin("StartBootPhaseLockSettingsReady");
mSystemServiceManager.startBootPhase(t, SystemService.PHASE_LOCK_SETTINGS_READY);
t.traceEnd();
// Create initial user if needed, which should be done early since some system services rely
// on it in their setup, but likely needs to be done after LockSettingsService is ready.
final HsumBootUserInitializer hsumBootUserInitializer =
HsumBootUserInitializer.createInstance(
mActivityManagerService, mPackageManagerService, mContentResolver,
context.getResources().getBoolean(R.bool.config_isMainUserPermanentAdmin));
if (hsumBootUserInitializer != null) {
t.traceBegin("HsumBootUserInitializer.init");
hsumBootUserInitializer.init(t);
t.traceEnd();
}
t.traceBegin("StartBootPhaseSystemServicesReady");
mSystemServiceManager.startBootPhase(t, SystemService.PHASE_SYSTEM_SERVICES_READY);
t.traceEnd();
t.traceBegin("MakeWindowManagerServiceReady");
try {
wm.systemReady();
} catch (Throwable e) {
reportWtf("making Window Manager Service ready", e);
}
t.traceEnd();
t.traceBegin("RegisterLogMteState");
try {
LogMteState.register(context);
} catch (Throwable e) {
reportWtf("RegisterLogMteState", e);
}
t.traceEnd();
// Emit any pending system_server WTFs
synchronized (SystemService.class) {
if (sPendingWtfs != null) {
mActivityManagerService.schedulePendingSystemServerWtfs(sPendingWtfs);
sPendingWtfs = null;
}
}
if (safeMode) {
mActivityManagerService.showSafeModeOverlay();
}
// Update the configuration for this context by hand, because we're going
// to start using it before the config change done in wm.systemReady() will
// propagate to it.
final Configuration config = wm.computeNewConfiguration(DEFAULT_DISPLAY);
DisplayMetrics metrics = new DisplayMetrics();
context.getDisplay().getMetrics(metrics);
context.getResources().updateConfiguration(config, metrics);
// The system context's theme may be configuration-dependent.
final Theme systemTheme = context.getTheme();
if (systemTheme.getChangingConfigurations() != 0) {
systemTheme.rebase();
}
// Permission policy service
t.traceBegin("StartPermissionPolicyService");
mSystemServiceManager.startService(PermissionPolicyService.class);
t.traceEnd();
t.traceBegin("MakePackageManagerServiceReady");
mPackageManagerService.systemReady();
t.traceEnd();
t.traceBegin("MakeDisplayManagerServiceReady");
try {
// TODO: use boot phase and communicate this flag some other way
mDisplayManagerService.systemReady(safeMode);
} catch (Throwable e) {
reportWtf("making Display Manager Service ready", e);
}
t.traceEnd();
mSystemServiceManager.setSafeMode(safeMode);
// Start device specific services
t.traceBegin("StartDeviceSpecificServices");
final String[] classes = mSystemContext.getResources().getStringArray(
R.array.config_deviceSpecificSystemServices);
for (final String className : classes) {
t.traceBegin("StartDeviceSpecificServices " + className);
try {
mSystemServiceManager.startService(className);
} catch (Throwable e) {
reportWtf("starting " + className, e);
}
t.traceEnd();
}
t.traceEnd();
t.traceBegin("GameManagerService");
mSystemServiceManager.startService(GAME_MANAGER_SERVICE_CLASS);
t.traceEnd();
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_UWB)) {
t.traceBegin("UwbService");
mSystemServiceManager.startServiceFromJar(UWB_SERVICE_CLASS, UWB_APEX_SERVICE_JAR_PATH);
t.traceEnd();
}
t.traceBegin("StartBootPhaseDeviceSpecificServicesReady");
mSystemServiceManager.startBootPhase(t, SystemService.PHASE_DEVICE_SPECIFIC_SERVICES_READY);
t.traceEnd();
t.traceBegin("StartSafetyCenterService");
mSystemServiceManager.startService(SAFETY_CENTER_SERVICE_CLASS);
t.traceEnd();
t.traceBegin("AppSearchModule");
mSystemServiceManager.startService(APPSEARCH_MODULE_LIFECYCLE_CLASS);
t.traceEnd();
if (SystemProperties.getBoolean("ro.config.isolated_compilation_enabled", false)) {
t.traceBegin("IsolatedCompilationService");
mSystemServiceManager.startService(ISOLATED_COMPILATION_SERVICE_CLASS);
t.traceEnd();
}
t.traceBegin("StartMediaCommunicationService");
mSystemServiceManager.startService(MEDIA_COMMUNICATION_SERVICE_CLASS);
t.traceEnd();
t.traceBegin("AppCompatOverridesService");
mSystemServiceManager.startService(APP_COMPAT_OVERRIDES_SERVICE_CLASS);
t.traceEnd();
t.traceBegin("HealthConnectManagerService");
mSystemServiceManager.startService(HEALTHCONNECT_MANAGER_SERVICE_CLASS);
t.traceEnd();
// These are needed to propagate to the runnable below.
final NetworkManagementService networkManagementF = networkManagement;
final NetworkPolicyManagerService networkPolicyF = networkPolicy;
final CountryDetectorService countryDetectorF = countryDetector;
final NetworkTimeUpdateService networkTimeUpdaterF = networkTimeUpdater;
final InputManagerService inputManagerF = inputManager;
final TelephonyRegistry telephonyRegistryF = telephonyRegistry;
final MediaRouterService mediaRouterF = mediaRouter;
final MmsServiceBroker mmsServiceF = mmsService;
final VpnManagerService vpnManagerF = vpnManager;
final VcnManagementService vcnManagementF = vcnManagement;
final WindowManagerService windowManagerF = wm;
final ConnectivityManager connectivityF = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
// 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");
t.traceBegin("StartActivityManagerReadyPhase");
mSystemServiceManager.startBootPhase(t, SystemService.PHASE_ACTIVITY_MANAGER_READY);
t.traceEnd();
t.traceBegin("StartObservingNativeCrashes");
try {
// 1.监控Native的crash
mActivityManagerService.startObservingNativeCrashes();
} catch (Throwable e) {
reportWtf("observing native crashes", e);
}
t.traceEnd();
t.traceBegin("RegisterAppOpsPolicy");
try {
mActivityManagerService.setAppOpsPolicy(new AppOpsPolicy(mSystemContext));
} catch (Throwable e) {
reportWtf("registering app ops policy", e);
}
t.traceEnd();
// 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 (mWebViewUpdateService != null) {
webviewPrep = SystemServerInitThreadPool.submit(() -> {
Slog.i(TAG, WEBVIEW_PREPARATION);
TimingsTraceAndSlog traceLog = TimingsTraceAndSlog.newAsyncLog();
traceLog.traceBegin(WEBVIEW_PREPARATION);
ConcurrentUtils.waitForFutureNoInterrupt(mZygotePreload, "Zygote preload");
mZygotePreload = null;
// 2.启动WebView
mWebViewUpdateService.prepareWebViewInSystemServer();
traceLog.traceEnd();
}, WEBVIEW_PREPARATION);
}
boolean isAutomotive = mPackageManager
.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
if (isAutomotive) {
t.traceBegin("StartCarServiceHelperService");
final SystemService cshs = mSystemServiceManager
.startService(CAR_SERVICE_HELPER_SERVICE_CLASS);
if (cshs instanceof Dumpable) {
mDumper.addDumpable((Dumpable) cshs);
}
if (cshs instanceof DevicePolicySafetyChecker) {
dpms.setDevicePolicySafetyChecker((DevicePolicySafetyChecker) cshs);
}
t.traceEnd();
}
if (isWatch) {
t.traceBegin("StartWearService");
String wearServiceComponentNameString =
context.getString(R.string.config_wearServiceComponent);
if (!TextUtils.isEmpty(wearServiceComponentNameString)) {
ComponentName wearServiceComponentName = ComponentName.unflattenFromString(
wearServiceComponentNameString);
if (wearServiceComponentName != null) {
Intent intent = new Intent();
intent.setComponent(wearServiceComponentName);
intent.addFlags(Intent.FLAG_DIRECT_BOOT_AUTO);
context.startServiceAsUser(intent, UserHandle.SYSTEM);
} else {
Slog.d(TAG, "Null wear service component name.");
}
}
t.traceEnd();
}
// 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) {
t.traceBegin("EnableAirplaneModeInSafeMode");
try {
connectivityF.setAirplaneMode(true);
} catch (Throwable e) {
reportWtf("enabling Airplane Mode during Safe Mode bootup", e);
}
t.traceEnd();
}
// 4.执行一系列服务的systemReady方法
t.traceBegin("MakeNetworkManagementServiceReady");
try {
if (networkManagementF != null) {
networkManagementF.systemReady();
}
} catch (Throwable e) {
reportWtf("making Network Managment Service ready", e);
}
CountDownLatch networkPolicyInitReadySignal = null;
if (networkPolicyF != null) {
networkPolicyInitReadySignal = networkPolicyF
.networkScoreAndNetworkManagementServiceReady();
}
t.traceEnd();
t.traceBegin("MakeConnectivityServiceReady");
try {
if (connectivityF != null) {
connectivityF.systemReady();
}
} catch (Throwable e) {
reportWtf("making Connectivity Service ready", e);
}
t.traceEnd();
t.traceBegin("MakeVpnManagerServiceReady");
try {
if (vpnManagerF != null) {
vpnManagerF.systemReady();
}
} catch (Throwable e) {
reportWtf("making VpnManagerService ready", e);
}
t.traceEnd();
t.traceBegin("MakeVcnManagementServiceReady");
try {
if (vcnManagementF != null) {
vcnManagementF.systemReady();
}
} catch (Throwable e) {
reportWtf("making VcnManagementService ready", e);
}
t.traceEnd();
t.traceBegin("MakeNetworkPolicyServiceReady");
try {
if (networkPolicyF != null) {
networkPolicyF.systemReady(networkPolicyInitReadySignal);
}
} catch (Throwable e) {
reportWtf("making Network Policy Service ready", e);
}
t.traceEnd();
// Wait for all packages to be prepared
mPackageManagerService.waitForAppDataPrepared();
// It is now okay to let the various system services start their
// third party code...
t.traceBegin("PhaseThirdPartyAppsCanStart");
// confirm webview completion before starting 3rd party
if (webviewPrep != null) {
ConcurrentUtils.waitForFutureNoInterrupt(webviewPrep, WEBVIEW_PREPARATION);
}
mSystemServiceManager.startBootPhase(t, SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
t.traceEnd();
// 5.执行一系列服务的systemRunning方法
if (hsumBootUserInitializer != null) {
t.traceBegin("HsumBootUserInitializer.systemRunning");
hsumBootUserInitializer.systemRunning(t);
t.traceEnd();
}
t.traceBegin("StartNetworkStack");
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();
} catch (Throwable e) {
reportWtf("starting Network Stack", e);
}
t.traceEnd();
t.traceBegin("StartTethering");
try {
// TODO: hide implementation details, b/146312721.
ConnectivityModuleConnector.getInstance().startModuleService(
TETHERING_CONNECTOR_CLASS,
PERMISSION_MAINLINE_NETWORK_STACK, service -> {
ServiceManager.addService(Context.TETHERING_SERVICE, service,
false /* allowIsolated */,
DUMP_FLAG_PRIORITY_HIGH | DUMP_FLAG_PRIORITY_NORMAL);
});
} catch (Throwable e) {
reportWtf("starting Tethering", e);
}
t.traceEnd();
t.traceBegin("MakeCountryDetectionServiceReady");
try {
if (countryDetectorF != null) {
countryDetectorF.systemRunning();
}
} catch (Throwable e) {
reportWtf("Notifying CountryDetectorService running", e);
}
t.traceEnd();
t.traceBegin("MakeNetworkTimeUpdateReady");
try {
if (networkTimeUpdaterF != null) {
networkTimeUpdaterF.systemRunning();
}
} catch (Throwable e) {
reportWtf("Notifying NetworkTimeService running", e);
}
t.traceEnd();
t.traceBegin("MakeInputManagerServiceReady");
try {
// TODO(BT) Pass parameter to input manager
if (inputManagerF != null) {
inputManagerF.systemRunning();
}
} catch (Throwable e) {
reportWtf("Notifying InputManagerService running", e);
}
t.traceEnd();
t.traceBegin("MakeTelephonyRegistryReady");
try {
if (telephonyRegistryF != null) {
telephonyRegistryF.systemRunning();
}
} catch (Throwable e) {
reportWtf("Notifying TelephonyRegistry running", e);
}
t.traceEnd();
t.traceBegin("MakeMediaRouterServiceReady");
try {
if (mediaRouterF != null) {
mediaRouterF.systemRunning();
}
} catch (Throwable e) {
reportWtf("Notifying MediaRouterService running", e);
}
t.traceEnd();
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
t.traceBegin("MakeMmsServiceReady");
try {
if (mmsServiceF != null) mmsServiceF.systemRunning();
} catch (Throwable e) {
reportWtf("Notifying MmsService running", e);
}
t.traceEnd();
}
t.traceBegin("IncidentDaemonReady");
try {
// TODO: Switch from checkService to getService once it's always
// in the build and should reliably be there.
final IIncidentManager incident = IIncidentManager.Stub.asInterface(
ServiceManager.getService(Context.INCIDENT_SERVICE));
if (incident != null) {
incident.systemRunning();
}
} catch (Throwable e) {
reportWtf("Notifying incident daemon running", e);
}
t.traceEnd();
if (mIncrementalServiceHandle != 0) {
t.traceBegin("MakeIncrementalServiceReady");
setIncrementalServiceSystemReady(mIncrementalServiceHandle);
t.traceEnd();
}
t.traceBegin("OdsignStatsLogger");
try {
OdsignStatsLogger.triggerStatsWrite();
} catch (Throwable e) {
reportWtf("Triggering OdsignStatsLogger", e);
}
t.traceEnd();
}, t);
t.traceBegin("LockSettingsThirdPartyAppsStarted");
LockSettingsInternal lockSettingsInternal =
LocalServices.getService(LockSettingsInternal.class);
if (lockSettingsInternal != null) {
lockSettingsInternal.onThirdPartyAppsStarted();
}
t.traceEnd();
t.traceBegin("StartSystemUI");
try {
// 3.开启系统界面
startSystemUi(context, windowManagerF);
} catch (Throwable e) {
reportWtf("starting System UI", e);
}
t.traceEnd();
t.traceEnd(); // startOtherServices
}
6.4 AMS启动过程
由于ams的重要性,这里接着startBootstrapServices()单独讲一下
ATMS创建流程:
- SystemServer:依次调用 main()、run()、startBootstrapServices(),再调用 SystemServiceManager 的 startService() 方法,并将 Lifecyle.class 传入;
- SystemServiceManager :startService() 方法通过反射调用 Lifecyle 的构造方法,生成 Lifecyle 对象;
- Lifecyle:构造方法中调用 ATMS 的构造方法创建 ATMS 对象,并通过 getService() 方法返回 ATMS 对象。
ActivityTaskManagerService简称ATMS,Android10中引入新功能,用来管理Activity的启动、调度等功能。紧接上面的流程,在SystemServer在startBootstrapServices()方法中会去启动ATMS。
从《SystemServiceManager()》中,可以知道SystemServiceManager.startService()最终调用的是启动对象中的onStart方法,因此ATM启动,这里最终会调用ActivityTaskManagerService.Lifecycle.onStart()来启动ATMS服务:
注意到atms和ams传入的是Lifecycle.class,我们来看看为什么需要这样做:
// /frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
// 静态内部类,继承SystemService,说明它是一个系统service
public static final class Lifecycle extends SystemService {
private final ActivityTaskManagerService mService;
public Lifecycle(Context context) {
// 这个context是SystemServiceManager传递过来的系统上下文,
// 即ContextImpl.getSystemContext()返回的实例
super(context);
// 1.创建ActivityTaskManagerService对象
mService = new ActivityTaskManagerService(context);
}
@Override
public void onStart() {
// 由SystemService调用ServiceManager.addService()加入到servicemanager进程中管理
publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
// 2.启动ATMS服务
mService.start();
}
@Override
public void onUserUnlocked(@NonNull TargetUser user) {
synchronized (mService.getGlobalLock()) {
mService.mTaskSupervisor.onUserUnlocked(user.getUserIdentifier());
}
}
@Override
public void onUserStopped(@NonNull TargetUser user) {
synchronized (mService.getGlobalLock()) {
mService.mTaskSupervisor.mLaunchParamsPersister
.onCleanupUser(user.getUserIdentifier());
}
}
// 返回的是new的ActivityTaskManagerService实例,SystemSever中使用
// SystemServiceManager.startService()后调用的getService()就是调用该方法
public ActivityTaskManagerService getService() {
return mService;
}
}
6.4.1 创建ActivityTaskManagerService
ActivityTaskManagerService简称ATMS,Android10新引入功能,用来管理Activity的启动、调度等功能。
Android 10中把原先在AMS中activity的管理移动到ATMS中,从Android 10的代码路径可以看出,管理Activity的ATMS被放入到的wm路径中,这个路径原先归WindowManagerService控制,谷歌的目的也是希望在将来把activity和window融合在一起,减少冗余代码以及AMS和WMS的协调工作。
- ATMS的路径为:frameworks/base/services/core/java/com/android/server/wm
- AMS的路径为:frameworks/base/services/core/java/com/android/server/am
/**
* This Context is themable and meant for UI display (AlertDialogs, etc.). The theme can
* change at runtime. Use mContext for non-UI purposes.
*/
private final Context mUiContext;
final ActivityThread mSystemThread;
...
@VisibleForTesting
final ActivityTaskManagerInternal mInternal;
...
// ActivityStackSupervisor 是ATM中用来管理Activity启动和调度的核心类
ActivityTaskSupervisor mTaskSupervisor;
...
//Activity 容器的根节点
RootWindowContainer mRootWindowContainer;
// WMS 负责窗口的管理
WindowManagerService mWindowManager;
....
/** This is the process holding what we currently consider to be the "home" activity. */
// 这是我们目前认为是"Home" Activity的过程
volatile WindowProcessController mHomeProcess;
...
@VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
public ActivityTaskManagerService(Context context) {
// 拿到System Context
mContext = context;
mFactoryTest = FactoryTest.getMode();
// 取出的是ActivityThread的静态变量sCurrentActivityThread
// 这意味着mSystemThread与SystemServer中的ActivityThread一致
mSystemThread = ActivityThread.currentActivityThread();
// 拿到System UI Context
mUiContext = mSystemThread.getSystemUiContext();
mLifecycleManager = new ClientLifecycleManager();
mVisibleActivityProcessTracker = new VisibleActivityProcessTracker(this);
// 拿到LocalService的对象
mInternal = new LocalService(); //ActivityTaskManagerInternal 的子类
GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
mWindowOrganizerController = new WindowOrganizerController(this);
mTaskOrganizerController = mWindowOrganizerController.mTaskOrganizerController;
mTaskFragmentOrganizerController =
mWindowOrganizerController.mTaskFragmentOrganizerController;
mBackNavigationController = new BackNavigationController();
}
在ActivityTaskManagerService的构造方法中初始化了ActivityThread实例,它的使用会在之后慢慢展开,此处给出ActivityThread的官方解释:它管理应用程序进程中主线程的执行、调度和执行activities、broadcasts和其他ActivityManagerService请求的其他操作。
ActivityTaskManagerService.start()
该方法在启动ActivityTaskManagerService时会被调用,在Lifecycle.onStart()中调用了该start()。
// /frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
private void start() {
LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
}
mInternal是创建的LocalService对象,它是ActivityTaskManagerService的内部类,继承了ActivityTaskManagerInternal的抽象类。这里的addService()方法会将ActivityTaskManagerInternal添加到本地服务的全局注册表中。
Activity Task manager的本地系统服务接口,只能在system server进程中使用。它的接口定义如下:
// /frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerInternal.java
/**
* Activity Task manager local system service interface.
* @hide Only for use within system server
*/
public abstract class ActivityTaskManagerInternal {
...
public interface ScreenObserver {
void onAwakeStateChanged(boolean isAwake);
void onKeyguardStateChanged(boolean isShowing);
}
....
/**
* Returns home activity for the specified user.
*
* @param userId ID of the user or {@link android.os.UserHandle#USER_ALL}
*/
public abstract ComponentName getHomeActivityForUser(int userId);
...
/**
* Start activity {@code intents} as if {@code packageName/featureId} on user {@code userId} did
* it.
*
* - DO NOT call it with the calling UID cleared.
* - All the necessary caller permission checks must be done at callsites.
*
* @return error codes used by {@link IActivityManager#startActivity} and its siblings.
*/
public abstract int startActivitiesAsPackage(String packageName, String featureId,
int userId, Intent[] intents, Bundle bOptions);
...
/**
* Registers a {@link ScreenObserver}.
*/
public abstract void registerScreenObserver(ScreenObserver observer);
...
public final class ActivityTokens {
private final @NonNull IBinder mActivityToken;
private final @NonNull IBinder mAssistToken;
private final @NonNull IBinder mShareableActivityToken;
private final @NonNull IApplicationThread mAppThread;
...
}
...
/** @return The intent used to launch the home activity. */
public abstract Intent getHomeIntent();
...
public abstract boolean startHomeActivity(int userId, String reason);
...
}
ActivityManagerService启动过程
SystemServer中startBootstrapServices()方法启动ATMS后,紧接就是去启动AMS。在Android 10的版本中,Activity的管理和调度移到ATMS中,AMS负责 service,broadcast,provider的管理和调度。
从《SystemServiceManager()》中,可以知道SystemServiceManager.startService()最终调用的是启动对象中的onStart方法,因此AMS启动,这里最终会调用ActivityTaskManagerService.Lifecycle.onStart()来启动AMS服务:
// /frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
public static final class Lifecycle extends SystemService {
private final ActivityManagerService mService;
private static ActivityTaskManagerService sAtm;
public Lifecycle(Context context) {
super(context);
// 1.创建ActivityManagerService,得到对象,传入ATM的对象
mService = new ActivityManagerService(context, sAtm);
}
public static ActivityManagerService startService(
SystemServiceManager ssm, ActivityTaskManagerService atm) {
sAtm = atm;
return ssm.startService(ActivityManagerService.Lifecycle.class).getService();
}
@Override
public void onStart() {
// 2.启动AMS服务
mService.start();
}
@Override
public void onBootPhase(int phase) {
mService.mBootPhase = phase;
if (phase == PHASE_SYSTEM_SERVICES_READY) {
mService.mBatteryStatsService.systemServicesReady();
mService.mServices.systemServicesReady();
} else if (phase == PHASE_ACTIVITY_MANAGER_READY) {
mService.startBroadcastObservers();
} else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
mService.mPackageWatchdog.onPackagesReady();
}
}
@Override
public void onUserStopped(@NonNull TargetUser user) {
mService.mBatteryStatsService.onCleanupUser(user.getUserIdentifier());
}
public ActivityManagerService getService() {
return mService;
}
}
6.4.2 创建ActivityManagerService
Activity的管理和调度放入到ATMS中执行,AMS中保留service,broadcast,provider的管理和调度。构造函数初始化主要工作就是初始化一些变量,供之后的service,broadcast,provider的管理和调度。
// /frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
public class ActivityManagerService extends IActivityManager.Stub
implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback, ActivityManagerGlobalLock {
...
// 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, ActivityTaskManagerService atm) {
LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
mInjector = new Injector(systemContext);
// 系统上下文,由systemserver进程创建的,ContextImpl.getSystemContext()得到的
mContext = systemContext;
mFactoryTest = FactoryTest.getMode();
// 取出的是ActivityThread的静态变量sCurrentActivityThread
// 这意味着mSystemThread与SystemServer中的ActivityThread一致
mSystemThread = ActivityThread.currentActivityThread();
mUiContext = mSystemThread.getSystemUiContext();
Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
// mHandler和mUiHandler初始化
mHandlerThread = new ServiceThread(TAG,
THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
mHandlerThread.start();
// 处理AMS中消息的主力
mHandler = new MainHandler(mHandlerThread.getLooper());
// UiHandler对应于Android中的UiThreads
mUiHandler = mInjector.getUiHandler(this);
//mProcStartHandler初始化
mProcStartHandlerThread = new ServiceThread(TAG + ":procStart",
THREAD_PRIORITY_FOREGROUND, false /* allowIo */);
mProcStartHandlerThread.start();
mProcStartHandler = new ProcStartHandler(this, mProcStartHandlerThread.getLooper());
mConstants = new ActivityManagerConstants(mContext, this, mHandler);
final ActiveUids activeUids = new ActiveUids(this, true /* postChangesToAtm */);
mPlatformCompat = (PlatformCompat) ServiceManager.getService(
Context.PLATFORM_COMPAT_SERVICE);
mProcessList = mInjector.getProcessList(this);
mProcessList.init(this, activeUids, mPlatformCompat);
mAppProfiler = new AppProfiler(this, BackgroundThread.getHandler().getLooper(),
new LowMemDetector(this));
mPhantomProcessList = new PhantomProcessList(this);
mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids);
// Broadcast policy parameters
final BroadcastConstants foreConstants = new BroadcastConstants(
Settings.Global.BROADCAST_FG_CONSTANTS);
foreConstants.TIMEOUT = BROADCAST_FG_TIMEOUT;
final BroadcastConstants backConstants = new BroadcastConstants(
Settings.Global.BROADCAST_BG_CONSTANTS);
backConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
final BroadcastConstants offloadConstants = new BroadcastConstants(
Settings.Global.BROADCAST_OFFLOAD_CONSTANTS);
offloadConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
// by default, no "slow" policy in this queue
offloadConstants.SLOW_TIME = Integer.MAX_VALUE;
mEnableOffloadQueue = SystemProperties.getBoolean(
"persist.device_config.activity_manager_native_boot.offload_queue_enabled", true);
mEnableModernQueue = foreConstants.MODERN_QUEUE_ENABLED;
if (mEnableModernQueue) {
mBroadcastQueues = new BroadcastQueue[1];
mBroadcastQueues[0] = new BroadcastQueueModernImpl(this, mHandler,
foreConstants, backConstants);
} else {
mBroadcastQueues = new BroadcastQueue[4];
// 创建 BroadcastQueue 前台广播对象,处理超时时长是 10s
mBroadcastQueues[BROADCAST_QUEUE_FG] = new BroadcastQueueImpl(this, mHandler,
"foreground", foreConstants, false, ProcessList.SCHED_GROUP_DEFAULT);
// 创建 BroadcastQueue 后台广播对象,处理超时时长是 60s
mBroadcastQueues[BROADCAST_QUEUE_BG] = new BroadcastQueueImpl(this, mHandler,
"background", backConstants, true, ProcessList.SCHED_GROUP_BACKGROUND);
//创建 BroadcastQueue 分流广播对象,处理超时时长是 60s
mBroadcastQueues[BROADCAST_QUEUE_BG_OFFLOAD] = new BroadcastQueueImpl(this, mHandler,
"offload_bg", offloadConstants, true, ProcessList.SCHED_GROUP_BACKGROUND);
mBroadcastQueues[BROADCAST_QUEUE_FG_OFFLOAD] = new BroadcastQueueImpl(this, mHandler,
"offload_fg", foreConstants, true, ProcessList.SCHED_GROUP_BACKGROUND);
}
// 创建 ActiveServices 对象,用于管理 ServiceRecord 对象
mServices = new ActiveServices(this);
mCpHelper = new ContentProviderHelper(this, true);
mPackageWatchdog = PackageWatchdog.getInstance(mUiContext);
mAppErrors = new AppErrors(mUiContext, this, mPackageWatchdog);
mUidObserverController = new UidObserverController(mUiHandler);
final File systemDir = SystemServiceManager.ensureSystemDir();
// TODO: Move creation of battery stats service outside of activity manager service.
// 初始化BatteryStatsService
mBatteryStatsService = BatteryStatsService.create(systemContext, systemDir,
BackgroundThread.getHandler(), this);
mOnBattery = DEBUG_POWER ? true
: mBatteryStatsService.getActiveStatistics().getIsOnBattery();
mOomAdjProfiler.batteryPowerChanged(mOnBattery);
mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops_accesses.xml"),
new File(systemDir, "appops.xml"), mHandler);
mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
mUserController = new UserController(this);
mInjector.mUserController = mUserController;
mPendingIntentController = new PendingIntentController(
mHandlerThread.getLooper(), mUserController, mConstants);
mAppRestrictionController = new AppRestrictionController(mContext, this);
mUseFifoUiScheduling = SystemProperties.getInt("sys.use_fifo_ui", 0) != 0;
mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
// 持有atm引用,并调用其initialize()
mActivityTaskManager = atm;
// 进一步初始化 ATMS
mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController,
DisplayThread.get().getLooper());
// 获取其local service对象
mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);
mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext);
Watchdog.getInstance().addMonitor(this);
Watchdog.getInstance().addThread(mHandler);
// bind background threads 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(OOM_ADJ_REASON_SYSTEM_INIT);
try {
Process.setThreadGroupAndCpuset(BackgroundThread.get().getThreadId(),
Process.THREAD_GROUP_SYSTEM);
Process.setThreadGroupAndCpuset(
mOomAdjuster.mCachedAppOptimizer.mCachedAppOptimizerThread.getThreadId(),
Process.THREAD_GROUP_SYSTEM);
} catch (Exception e) {
Slog.w(TAG, "Setting background thread cpuset failed");
}
mInternal = new LocalService();
mPendingStartActivityUids = new PendingStartActivityUids();
mTraceErrorLogger = new TraceErrorLogger();
mComponentAliasResolver = new ComponentAliasResolver(this);
}
ActivityManagerService.start()
该方法主要工作有:
启动CPU监控线程,在启动CPU监控线程之前,首先将进程复位;- 注册电池状态服务和权限管理服务。
// /frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
private void start() {
// 注册电池状态和权限管理服务
mBatteryStatsService.publish();
mAppOpsService.publish();
mProcessStats.publish();
Slog.d("AppOps", "AppOpsService published");
LocalServices.addService(ActivityManagerInternal.class, mInternal);
LocalManagerRegistry.addManager(ActivityManagerLocal.class,
(ActivityManagerLocal) mInternal);
mActivityTaskManager.onActivityManagerInternalAdded();
mPendingIntentController.onActivityManagerInternalAdded();
mAppProfiler.onActivityManagerInternalAdded();
CriticalEventLog.init();
}
AMS设置SystemServiceManager和Installer
继续回到《1.3 启动核心服务》中,在启动完ATMS和AMS后,会去设置SystemServiceManager和Installer:
这里会去调用AMS中对应的方法:
// /frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
public class ActivityManagerService extends IActivityManager.Stub
implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback, ActivityManagerGlobalLock {
...
public void setSystemServiceManager(SystemServiceManager mgr) {
mSystemServiceManager = mgr;
}
public void setInstaller(Installer installer) {
mInstaller = installer;
}
...
}
这里只是简单地将两个对象保存到AMS中,后续会用到。
获取ATMS的全局Lock
继续回到《启动核心服务》中:
// frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
...
/* Global service lock used by the package the owns this service. */
final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
...
public WindowManagerGlobalLock getGlobalLock() {
return mGlobalLock;
}
}
----------------
// frameworks/base/services/core/java/com/android/server/wm/WindowManagerGlobalLock.java
/**
* Class that is used to generate an instance of the WM global lock. We are only doing this because
* we need a class for the pattern used in frameworks/base/services/core/Android.bp for CPU boost
* in the WM critical section.
*/
public class WindowManagerGlobalLock {
}
AMS.initPowerManagement()
继续回到《启动核心服务》中:
调用AMS中的方法:
// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
public class ActivityManagerService extends IActivityManager.Stub
implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback, ActivityManagerGlobalLock {
...
public void initPowerManagement() {
mActivityTaskManager.onInitPowerManagement();
mBatteryStatsService.initPowerManagement();
// AMS持有PowerMManagerInternal service引用
mLocalPowerManager = LocalServices.getService(PowerManagerInternal.class);
}
...
}
ATMS同AMS一样,也持有PowerManagerInternal service引用,ATMS.onInitPowerManagement()如下:
// /frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
public void onInitPowerManagement() {
synchronized (mGlobalLock) {
mTaskSupervisor.initPowerManagement();
final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
// 持有PowerManagerInternal service引用
mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
mVoiceWakeLock.setReferenceCounted(false);
}
}
...
}
继续initPowerManagement()方法:
// /frameworks/base/services/core/java/com/android/server/am/BatteryStatsService.java
/**
* All information we are collecting about things that can happen that impact
* battery life.
*/
public final class BatteryStatsService extends IBatteryStats.Stub
implements PowerManagerInternal.LowPowerModeListener,
BatteryStatsImpl.PlatformIdleStateCallback,
BatteryStatsImpl.EnergyStatsRetriever,
Watchdog.Monitor {
/**
* At the time when the constructor runs, the power manager has not yet been
* initialized. So we initialize the low power observer later.
*/
public void initPowerManagement() {
// 持有PowerManagerInternal service引用,并注册低电量模式监听
final PowerManagerInternal powerMgr = LocalServices.getService(PowerManagerInternal.class);
powerMgr.registerLowPowerModeObserver(this);
synchronized (mStats) {
mStats.notePowerSaveModeLockedInit(
powerMgr.getLowPowerState(ServiceType.BATTERY_STATS).batterySaverEnabled,
SystemClock.elapsedRealtime(), SystemClock.uptimeMillis());
}
(new WakeupReasonThread()).start();
}
}
该方法主要业务:
- 把AMS作为name = activity添加到systemserver进程中管理;
- 注册procstats服务(进程状态),meminfo服务(内存信息),gfxinfo服务(图像信息),dbinfo服务(数据库信息),cpuinfo服务(cup信息),permission服务(权限控制信息),processinfo服务(进程信息),cacheinfo服务(cache信息)注册到systemserver进程中进行管理;
- 获取package=“android”的ApplicationInfo,为ActivityThread安装相关system application信息;
- 为systemserver 主进程开辟一个ProcessRecord来维护进程的相关信息。
// /frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
public void setSystemProcess() {
try {
// 1.注册一些服务到ServiceManager:
// 包括 activity、procstats、meminfo、gfxinfo、dbinfo、permission、processinfo
// 把AMS注册到systemserver进程中管理:activity
ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
// 注册进程状态服务:procstats
ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
// 注册内存信息服务:meminfo
ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false,
DUMP_FLAG_PRIORITY_HIGH);
// 注册图像信息服务和数据库信息服务:gfxinfo,dbinfo
ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
ServiceManager.addService("dbinfo", new DbBinder(this));
// 注册cupinfo服务到systemserver进程中,CUP信息
mAppProfiler.setCpuInfoService();
// 注册权限服务、进程信息服务、缓存信息服务:permission,processinfo,cacheinfo
ServiceManager.addService("permission", new PermissionController(this));
ServiceManager.addService("processinfo", new ProcessInfoService(this));
ServiceManager.addService("cacheinfo", new CacheBinder(this));
// 2.通过解析framework-res.apk里的AndroidManifest.xml获得ApplicationInfo
ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
"android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
// 3.为ActivityThread 安装 system application相关信息,
// 将framework-res.apk对应的ApplicationInfo安装到LoadedApk中的mApplicationInfo
mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
// 4.为systemserver主进程开辟一个ProcessRecord来维护进程的相关信息
synchronized (this) {
ProcessRecord app = mProcessList.newProcessRecordLocked(info, info.processName,
false,
0,
false,
0,
null,
new HostingRecord(HostingRecord.HOSTING_TYPE_SYSTEM));
app.setPersistent(true);
app.setPid(MY_PID);
app.mState.setMaxAdj(ProcessList.SYSTEM_ADJ);
app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
app.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_SYSTEM);
addPidLocked(app);
updateLruProcessLocked(app, false, null);
updateOomAdjLocked(OOM_ADJ_REASON_SYSTEM_INIT);
}
} 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 (getAppOpsManager().checkOpNoThrow(op, uid, packageName)
!= AppOpsManager.MODE_ALLOWED) {
runInBackgroundDisabled(uid);
}
}
}
});
final int[] cameraOp = {AppOpsManager.OP_CAMERA};
mAppOpsService.startWatchingActive(cameraOp, new IAppOpsActiveCallback.Stub() {
@Override
public void opActiveChanged(int op, int uid, String packageName, String attributionTag,
boolean active, @AttributionFlags int attributionFlags,
int attributionChainId) {
cameraActiveChanged(uid, active);
}
});
}
getApplicationInfo()
这里会通过PackageManagerService.java的getApplicationInfo()方法去获取Application的信息:
获取package="android"的ApplicationInfo,为ActivityThread安装相关system application信息;在后边的章节中介绍了AMS的这个mSystemThread,这个实际上是systemserver进程的主线程,所以此处是在systemserver进程中安装了framework-res.apk,(之后系统还会安装SettingsProvider.apk)。
此处安装的是framework-res.apk。因为只有该apk的AndroidManifest.xml中package="android"且是SYSTEM_UID,如下:
// frameworks/base/core/res/AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<!--
/* //device/apps/common/AndroidManifest.xml
**
** Copyright 2006, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="android" coreApp="true" android:sharedUserId="android.uid.system"
android:sharedUserLabel="@string/android_system_label">
<!-- ================================================ -->
<!-- Special broadcasts that only the system can send -->
<!-- ================================================ -->
<eat-comment />
installSystemApplicationInfo()
这里会通过ActivityThread.java的installSystemApplicationInfo()方法安装system application的信息:
继续调用ActivityThread.java中的方法:
// /frameworks/base/core/java/android/app/ActivityThread.java
public void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) {
synchronized (this) {
getSystemContext().installSystemApplicationInfo(info, classLoader);
getSystemUiContext().installSystemApplicationInfo(info, classLoader);
// give ourselves a default profiler
mProfiler = new Profiler();
}
}
6.5 AMS.systemReady()
经过分析,已经梳理出了AMS和ATMS的启动过程。这里再回到《SystemServer启动》中,在SystemServer的run()方法中,在调用startBootstrapServices()启动完AMS和ATMS服务后,会在startOtherServices()中启动完其他的服务之后,调用AMS的systemReady()方法去作一些准备工作。
AMS的systemReady处理分为三个阶段:
- 阶段1:主要是调用一些关键服务的初始化函数, 然后杀死那些没有FLAG_PERSISTENT却在AMS启动完成前已经存在的进程, 同时获取一些配置参数。 需要注意的是,由于只有Java进程才会向AMS注册,而一般的Native进程不会向AMS注册,因此此处杀死的进程是Java进程。
- 阶段2:执行goingCallback的处理,主要的工作就是通知一些服务可以进行systemReady、systemRunning相关的工作,并进行启动服务或应用进程的工作。
- 阶段3:启动Home Activity,当启动结束,并发送ACTION_BOOT_COMPLETED广播时,AMS的启动过程告一段落。
// frameworks/base/services/java/com/android/server/SystemServer.java
private void startOtherServices() {
mActivityManagerService.systemReady(() -> {xxxxxgoingCallbackxxx, BOOT_TIMINGS_TRACE_LOG);
}
// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
阶段1:关键服务的初始化
阶段2:goingCallback处理
阶段3:启动Home Activity,完成AMS启动
}
6.5.1systemReady阶段1
主要是调用一些关键服务的初始化函数, 然后杀死那些没有FLAG_PERSISTENT却在AMS启动完成前已经存在的进程, 同时获取一些配置参数。 需要注意的是,由于只有Java进程才会向AMS注册,而一般的Native进程不会向AMS注册,因此此处杀死的进程是Java进程。
// /frameworks/base/services/java/com/android/server/SystemServer.java
/**
* Ready. Set. Go!
*/
public void systemReady(final Runnable goingCallback, @NonNull TimingsTraceAndSlog t) {
t.traceBegin("PhaseActivityManagerReady");
mSystemServiceManager.preSystemReady();
synchronized(this) {
// 第一次进入mSystemReady 为false,不走该流程
if (mSystemReady) {
// If we're done calling all the receivers, run the next "boot phase" passed in
// by the SystemServer
if (goingCallback != null) {
goingCallback.run();
}
t.traceEnd(); // PhaseActivityManagerReady
return;
}
t.traceBegin("controllersReady");
mLocalDeviceIdleController =
LocalServices.getService(DeviceIdleInternal.class);
// 这一部分主要是调用一些关键服务SystemReady相关的函数,
// 进行一些等待AMS初始完,才能进行的工作
mActivityTaskManager.onSystemReady();
// Make sure we have the current profile info, since it is needed for security checks.
mUserController.onSystemReady();
mAppOpsService.systemReady();
mProcessList.onSystemReady();
mAppRestrictionController.onSystemReady();
mSystemReady = true;
t.traceEnd();
}
try {
sTheRealBuildSerial = IDeviceIdentifiersPolicyService.Stub.asInterface(
ServiceManager.getService(Context.DEVICE_IDENTIFIERS_SERVICE))
.getSerial();
} catch (RemoteException e) {}
t.traceBegin("killProcesses");
ArrayList<ProcessRecord> procsToKill = null;
synchronized(mPidsSelfLocked) {
// mPidsSelfLocked中保存当前正在运行的所有进程的信息
for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
ProcessRecord proc = mPidsSelfLocked.valueAt(i);
//在AMS启动完成前,如果没有FLAG_PERSISTENT标志的进程已经启动了,
//就将这个进程加入到procsToKill中
if (!isAllowedWhileBooting(proc.info)) {
if (procsToKill == null) {
procsToKill = new ArrayList<ProcessRecord>();
}
procsToKill.add(proc);
}
}
}
// 收集已经启动的进程并杀死,排除persistent常驻进程
synchronized(this) {
// 利用removeProcessLocked关闭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);
mProcessList.removeProcessLocked(proc, true, false,
ApplicationExitInfo.REASON_OTHER,
ApplicationExitInfo.SUBREASON_SYSTEM_UPDATE_DONE,
"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;
}
t.traceEnd(); // KillProcesses
Slog.i(TAG, "System now ready");
EventLogTags.writeBootProgressAmsReady(SystemClock.uptimeMillis());
t.traceBegin("updateTopComponentForFactoryTest");
mAtmInternal.updateTopComponentForFactoryTest();
t.traceEnd();
t.traceBegin("registerActivityLaunchObserver");
mAtmInternal.getLaunchObserverRegistry().registerLaunchObserver(mActivityLaunchObserver);
t.traceEnd();
t.traceBegin("watchDeviceProvisioning");
watchDeviceProvisioning(mContext);
t.traceEnd();
t.traceBegin("retrieveSettings");
retrieveSettings();
t.traceEnd();
t.traceBegin("Ugm.onSystemReady");
mUgmInternal.onSystemReady();
t.traceEnd();
t.traceBegin("updateForceBackgroundCheck");
final PowerManagerInternal pmi = LocalServices.getService(PowerManagerInternal.class);
if (pmi != null) {
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.");
}
t.traceEnd();
// 1.调用参数传入的runnable对象,SystemServer中有具体的定义
if (goingCallback != null) goingCallback.run();
t.traceBegin("getCurrentUser"); // should be fast, but these methods acquire locks
// Check the current user here as a user can be started inside goingCallback.run() from
// other system services.
final int currentUserId = mUserController.getCurrentUserId();
Slog.i(TAG, "Current user:" + currentUserId);
if (currentUserId != UserHandle.USER_SYSTEM && !mUserController.isSystemUserStarted()) {
// User other than system user has started. Make sure that system user is already
// started before switching user.
throw new RuntimeException("System user not started while current user is:"
+ currentUserId);
}
t.traceEnd();
t.traceBegin("ActivityManagerStartApps");
mBatteryStatsService.onSystemReady();
mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,
Integer.toString(currentUserId), currentUserId);
mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,
Integer.toString(currentUserId), currentUserId);
// On Automotive / Headless System User Mode, at this point the system user has already been
// started and unlocked, and some of the tasks we do here have already been done. So skip
// those in that case. The duplicate system user start is guarded in SystemServiceManager.
// TODO(b/266158156): this workaround shouldn't be necessary once we move the headless-user
// start logic to UserManager-land.
mUserController.onSystemUserStarting();
synchronized (this) {
// Only start up encryption-aware persistent apps; once user is
// unlocked we'll come back around and start unaware apps
t.traceBegin("startPersistentApps");
// 2.启动persistent为1的application所在的进程
startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE);
t.traceEnd();
// 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 (SystemProperties.getBoolean(SYSTEM_USER_HOME_NEEDED, false)) {
t.traceBegin("enableHomeActivity");
ComponentName cName = new ComponentName(mContext, SystemUserHomeActivity.class);
try {
AppGlobals.getPackageManager().setComponentEnabledSetting(cName,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0,
UserHandle.USER_SYSTEM, "am");
} catch (RemoteException e) {
throw e.rethrowAsRuntimeException();
}
t.traceEnd();
}
boolean isBootingSystemUser = currentUserId == UserHandle.USER_SYSTEM;
// Some systems - like automotive - will explicitly unlock system user then switch
// to a secondary user.
// TODO(b/266158156): this workaround shouldn't be necessary once we move
// the headless-user start logic to UserManager-land.
// a.通过ATM,启动Home Activity
if (isBootingSystemUser && !UserManager.isHeadlessSystemUserMode()) {
t.traceBegin("startHomeOnAllDisplays");
mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");
t.traceEnd();
}
t.traceBegin("showSystemReadyErrorDialogs");
mAtmInternal.showSystemReadyErrorDialogsIfNeeded();
t.traceEnd();
// 调用所有系统服务的onStartUser接口
if (isBootingSystemUser) {
// Need to send the broadcasts for the system user here because
// UserController#startUserInternal will not send them for the system user starting,
// It checks if the user state already exists, which is always the case for the
// system user.
t.traceBegin("sendUserStartBroadcast");
final int callingUid = Binder.getCallingUid();
final int callingPid = Binder.getCallingPid();
final long ident = Binder.clearCallingIdentity();
try {
mUserController.sendUserStartedBroadcast(
currentUserId, callingUid, callingPid);
mUserController.sendUserStartingBroadcast(
currentUserId, callingUid, callingPid);
} catch (Throwable e) {
Slog.wtf(TAG, "Failed sending first user broadcasts", e);
} finally {
Binder.restoreCallingIdentity(ident);
}
t.traceEnd();
} else {
Slog.i(TAG, "Not sending multi-user broadcasts for non-system user "
+ currentUserId);
}
t.traceBegin("resumeTopActivities");
mAtmInternal.resumeTopActivities(false /* scheduleIdle */);
t.traceEnd();
if (isBootingSystemUser) {
t.traceBegin("sendUserSwitchBroadcasts");
mUserController.sendUserSwitchBroadcasts(-1, currentUserId);
t.traceEnd();
}
t.traceBegin("setBinderProxies");
BinderInternal.nSetBinderProxyCountWatermarks(BINDER_PROXY_HIGH_WATERMARK,
BINDER_PROXY_LOW_WATERMARK);
BinderInternal.nSetBinderProxyCountEnabled(true);
BinderInternal.setBinderProxyCountCallback(
(uid) -> {
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");
// We need to run a GC here, because killing the processes involved
// actually isn't guaranteed to free up the proxies; in fact, if the
// GC doesn't run for a long time, we may even exceed the global
// proxy limit for a process (20000), resulting in system_server itself
// being killed.
// Note that the GC here might not actually clean up all the proxies,
// because the binder reference decrements will come in asynchronously;
// but if new processes belonging to the UID keep adding proxies, we
// will get another callback here, and run the GC again - this time
// cleaning up the old proxies.
VMRuntime.getRuntime().requestConcurrentGC();
}
}, mHandler);
t.traceEnd(); // setBinderProxies
t.traceEnd(); // ActivityManagerStartApps
// Load the component aliases.
t.traceBegin("componentAlias");
mComponentAliasResolver.onSystemReady(mConstants.mEnableComponentAlias,
mConstants.mComponentAliasOverrides);
t.traceEnd(); // componentAlias
t.traceEnd(); // PhaseActivityManagerReady
}
}
6.5.2 systemReady阶段2
执行goingCallback的处理,主要的工作就是通知一些服务可以进行systemReady相关的工作,并进行启动服务或应用进程的工作。
// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
...
//1.调用参数传入的runnable对象,SystemServer中有具体的定义,参考[4.7.2.1]
if (goingCallback != null) goingCallback.run();
...
//调用所有系统服务的onStartUser接口
if (isBootingSystemUser) {
// Need to send the broadcasts for the system user here because
// UserController#startUserInternal will not send them for the system user starting,
// It checks if the user state already exists, which is always the case for the
// system user.
t.traceBegin("sendUserStartBroadcast");
final int callingUid = Binder.getCallingUid();
final int callingPid = Binder.getCallingPid();
final long ident = Binder.clearCallingIdentity();
try {
mUserController.sendUserStartedBroadcast(
currentUserId, callingUid, callingPid);
mUserController.sendUserStartingBroadcast(
currentUserId, callingUid, callingPid);
} catch (Throwable e) {
Slog.wtf(TAG, "Failed sending first user broadcasts", e);
} finally {
Binder.restoreCallingIdentity(ident);
}
t.traceEnd();
} else {
Slog.i(TAG, "Not sending multi-user broadcasts for non-system user "
+ currentUserId);
}
synchronized (this) {
//2.启动persistent为1的application所在的进程
startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE);
// Start up initial activity.
mBooting = true;
...
}
goingCallback.run()
监控Native的crash,启动WebView,执行一些服务的systemReady 和systemRunning方法。
具体在startOtherServices→mActivityManagerService.systemReady(() -> { … }1-5中
这里继续看一下startSystemUi()方法,启动systemUI服务,服务名称”com.android.systemui/.SystemUIService”:
// /frameworks/base/services/java/com/android/server/SystemServer.java
private static void startSystemUi(Context context, WindowManagerService windowManager) {
PackageManagerInternal pm = LocalServices.getService(PackageManagerInternal.class);
Intent intent = new Intent();
// 获取SystemUI的Component
intent.setComponent(pm.getSystemUiServiceComponent());
intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
//Slog.d(TAG, "Starting service: " + intent);
// 启动SystemUI服务
context.startServiceAsUser(intent, UserHandle.SYSTEM);
windowManager.onSystemUiStarted();
}
AMS.startPersistentApps()
// /frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
void startPersistentApps(int matchFlags) {
if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) return;
synchronized (this) {
try {
// 从PKMS中得到persistent为1的ApplicationInfo
final List<ApplicationInfo> apps = AppGlobals.getPackageManager()
.getPersistentApplications(STOCK_PM_FLAGS | matchFlags).getList();
for (ApplicationInfo app : apps) {
// 由于framework-res.apk已经由系统启动,所以此处不再启动它
if (!"android".equals(app.packageName)) {
final ProcessRecord proc = addAppLocked(
app, null, false, null /* ABI override */,
ZYGOTE_POLICY_FLAG_BATCH_LAUNCH);
if (proc != null) {
proc.mProfile.addHostingComponentType(
HOSTING_COMPONENT_TYPE_PERSISTENT);
}
}
}
} catch (RemoteException ex) {
}
}
}
systemReady阶段3
启动Home Activity,当启动结束,并发送ACTION_BOOT_COMPLETED广播时,AMS的启动过程告一段落。
ATMS.startHomeOnAllDisplays()
该方法用于启动Home Activity:
// /frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
@Override
public boolean startHomeOnAllDisplays(int userId, String reason) {
synchronized (mGlobalLock) {
// 调用RootWindowContainer的startHomeOnAllDisplays(),最终到startHomeOnDisplay()
return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
}
}
调用RootWindowContainer的startHomeOnAllDisplays()方法:
// /frameworks/base/services/core/java/com/android/server/wm/RootWindowContainer.java
boolean startHomeOnAllDisplays(int userId, String reason) {
boolean homeStarted = false;
for (int i = getChildCount() - 1; i >= 0; i--) {
final int displayId = getChildAt(i).mDisplayId;
homeStarted |= startHomeOnDisplay(userId, reason, displayId);
}
return homeStarted;
}
...
boolean startHomeOnDisplay(int userId, String reason, int displayId) {
return startHomeOnDisplay(userId, reason, displayId, false /* allowInstrumenting */,
false /* fromHomeKey */);
}
boolean startHomeOnDisplay(int userId, String reason, int displayId, boolean allowInstrumenting,
boolean fromHomeKey) {
// Fallback to top focused display or default display if the displayId is invalid.
if (displayId == INVALID_DISPLAY) {
final Task rootTask = getTopDisplayFocusedRootTask();
displayId = rootTask != null ? rootTask.getDisplayId() : DEFAULT_DISPLAY;
}
final DisplayContent display = getDisplayContent(displayId);
return display.reduceOnAllTaskDisplayAreas((taskDisplayArea, result) ->
result | startHomeOnTaskDisplayArea(userId, reason, taskDisplayArea,
allowInstrumenting, fromHomeKey),
false /* initValue */);
}
/**
* This starts home activity on display areas that can have system decorations based on
* displayId - default display area always uses primary home component.
* For secondary display areas, the home activity must have category SECONDARY_HOME and then
* resolves according to the priorities listed below.
* - If default home is not set, always use the secondary home defined in the config.
* - Use currently selected primary home activity.
* - Use the activity in the same package as currently selected primary home activity.
* If there are multiple activities matched, use first one.
* - Use the secondary home defined in the config.
*/
boolean startHomeOnTaskDisplayArea(int userId, String reason, TaskDisplayArea taskDisplayArea,
boolean allowInstrumenting, boolean fromHomeKey) {
// Fallback to top focused display area if the provided one is invalid.
if (taskDisplayArea == null) {
final Task rootTask = getTopDisplayFocusedRootTask();
taskDisplayArea = rootTask != null ? rootTask.getDisplayArea()
: getDefaultTaskDisplayArea();
}
Intent homeIntent = null;
ActivityInfo aInfo = null;
if (taskDisplayArea == getDefaultTaskDisplayArea()
|| mWmService.shouldPlacePrimaryHomeOnDisplay(
taskDisplayArea.getDisplayId(), userId)) {
homeIntent = mService.getHomeIntent();
// 根据intent中携带的ComponentName,利用PKMS得到ActivityInfo
aInfo = resolveHomeActivity(userId, homeIntent);
} else if (shouldPlaceSecondaryHomeOnDisplayArea(taskDisplayArea)) {
Pair<ActivityInfo, Intent> info = resolveSecondaryHomeActivity(userId, taskDisplayArea);
aInfo = info.first;
homeIntent = info.second;
}
if (aInfo == null || homeIntent == null) {
return false;
}
if (!canStartHomeOnDisplayArea(aInfo, taskDisplayArea, allowInstrumenting)) {
return false;
}
// Updates the home component of the intent.
homeIntent.setComponent(new ComponentName(aInfo.applicationInfo.packageName, aInfo.name));
homeIntent.setFlags(homeIntent.getFlags() | FLAG_ACTIVITY_NEW_TASK);
// Updates the extra information of the intent.
if (fromHomeKey) {
homeIntent.putExtra(WindowManagerPolicy.EXTRA_FROM_HOME_KEY, true);
if (mWindowManager.getRecentsAnimationController() != null) {
mWindowManager.getRecentsAnimationController().cancelAnimationForHomeStart();
}
}
homeIntent.putExtra(WindowManagerPolicy.EXTRA_START_REASON, reason);
// Update the reason for ANR debugging to verify if the user activity is the one that
// actually launched.
final String myReason = reason + ":" + userId + ":" + UserHandle.getUserId(
aInfo.applicationInfo.uid) + ":" + taskDisplayArea.getDisplayId();
// 启动Home Activity--Luncher
mService.getActivityStartController().startHomeActivity(homeIntent, aInfo, myReason,
taskDisplayArea);
return true;
}
startOtherServices()方法中会启动SystemUI,之后SystemServer通知AMS系统已准备好,此时AMS启动桌面并且发送BOOT_COMPLETED广播。至此,系统层面启动流程结束。
这里就分析到这,后面的详细分析后续另外单独分析。AMS和ATMS的启动流程分析完毕。
问题:
1、Android 系统启动流程?
A:当按电源键触发开机,首先会从 ROM 中预定义的地方加载引导程序 BootLoader 到 RAM 中,并执行 BootLoader 程序启动 Linux Kernel, 然后启动用户级别的第一个进程: init 进程。init 进程会解析init.rc 脚本做一些初始化工作,包括挂载文件系统、创建工作目录以及启动系统服务进程等,其中系统服务进程包括 Zygote、service manager、media 等。在 Zygote 中会进一步去启动 system_server 进程,然后在 system_server 进程中会启动 AMS、WMS、PMS 等服务,等这些服务启动之后,AMS 中就会打开 Launcher 应用的 home Activity,最终就看到了手机的 “桌面”。
2、system_server 为什么要在 Zygote 中启动,而不是由 init 直接启动呢?
A:Zygote 作为一个孵化器,可以提前加载一些资源,这样 fork() 时基于 Copy-On-Write 机制创建的其他进程就能直接使用这些资源,而不用重新加载。比如 system_server 就可以直接使用 Zygote 中的 JNI函数、共享库、常用的类、以及主题资源。
3、为什么要专门使用 Zygote 进程去孵化应用进程,而不是让 system_server 去孵化呢?
A:首先 system_server 相比 Zygote 多运行了 AMS、WMS 等服务,这些对一个应用程序来说是不需要的。另外进程的 fork() 对多线程不友好,仅会将发起调用的线程拷贝到子进程,这可能会导致死锁,而system_server 中肯定是有很多线程的。
4、具体是怎么导致死锁的?
在 POSIX 标准中,fork 的行为是这样的:复制整个用户空间的数据(通常使用 copy-on-write 的策略,所以可以实现的速度很快)以及所有系统对象,然后仅复制当前线程到子进程。这里:所有父进程中别的线程,到了子进程中都是突然蒸发掉的。对于锁来说,从 OS 看,每个锁有一个所有者,即最后一次 lock 它的线程。假设这么一个环境,在 fork之前,有一个子线程 lock 了某个锁,获得了对锁的所有权。fork 以后,在子进程中,所有的额外线程都人间蒸发了。而锁却被正常复制了,在子进程看来,这个锁没有主人,所以没有任何人可以对它解锁。当子进程想 lock 这个锁时,不再有任何手段可以解开了,程序发生死锁
5、Zygote 为什么不采用 Binder 机制进行 IPC 通信?
A:Binder 机制中存在 Binder 线程池,是多线程的,如果 Zygote 采用 Binder 的话就存在上面说的
fork() 与 多线程的问题了。其实严格来说,Binder 机制不一定要多线程,所谓的 Binder 线程只不过是在循环读取 Binder 驱动的消息而已,只注册一个 Binder 线程也是可以工作的,比如 service manager就是这样的。实际上 Zygote 尽管没有采取 Binder 机制,它也不是单线程的,但它在 fork() 前主动停止了其他线程,fork() 后重新启动了。
参考
Android开机全解析 - 简书 (jianshu.com)
android binder机制—ProcessState和线程池-CSDN博客
Android ActivityManagerService–01:AMS和ATMS启动过程 - 简书 (jianshu.com)