该篇章主要做了如下事情:
/frameworks/base/core/java/com/android/internal/os/
- ZygoteInit.java
- RuntimeInit.java
- Zygote.java
/frameworks/base/core/services/java/com/android/server/
- SystemServer.java
/frameworks/base/core/jni/
- com_android_internal_os_Zygote.cpp
- AndroidRuntime.cpp
/frameworks/base/cmds/app_process/App_main.cpp
准备fork系统进程的参数
/**
* Prepare the arguments and forks for the system server process.
*
* Returns an {@code Runnable} that provides an entrypoint into system_server code in the
* child process, and {@code null} in the parent.
*/
private static Runnable forkSystemServer(String abiList, String socketName,
ZygoteServer zygoteServer) {
long capabilities = posixCapabilitiesAsBits(
OsConstants.CAP_IPC_LOCK,
OsConstants.CAP_KILL,
OsConstants.CAP_NET_ADMIN,
OsConstants.CAP_NET_BIND_SERVICE,
OsConstants.CAP_NET_BROADCAST,
OsConstants.CAP_NET_RAW,
OsConstants.CAP_SYS_MODULE,
OsConstants.CAP_SYS_NICE,
OsConstants.CAP_SYS_PTRACE,
OsConstants.CAP_SYS_TIME,
OsConstants.CAP_SYS_TTY_CONFIG,
OsConstants.CAP_WAKE_ALARM,
OsConstants.CAP_BLOCK_SUSPEND
);
/* Containers run without some capabilities, so drop any caps that are not available. */
StructCapUserHeader header = new StructCapUserHeader(
OsConstants._LINUX_CAPABILITY_VERSION_3, 0);
//容器运行没有内容,就阻止一些无效的caps.
StructCapUserData[] data;
try {
data = Os.capget(header);
} catch (ErrnoException ex) {
throw new RuntimeException("Failed to capget()", ex);
}
capabilities &= ((long) data[0].effective) | (((long) data[1].effective) << 32);
/* Hardcoded command line to start the system server */
//通过硬编码启动system server
String args[] = {
"--setuid=1000",
"--setgid=1000",
"--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1023,1024,1032,1065,3001,3002,3003,3006,3007,3009,3010",
"--capabilities=" + capabilities + "," + capabilities,
"--nice-name=system_server",
"--runtime-args",
"--target-sdk-version=" + VMRuntime.SDK_VERSION_CUR_DEVELOPMENT,
"com.android.server.SystemServer",
};
ZygoteConnection.Arguments parsedArgs = null;
int pid;
try {
parsedArgs = new ZygoteConnection.Arguments(args);
ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);
ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);
boolean profileSystemServer = SystemProperties.getBoolean(
"dalvik.vm.profilesystemserver", false);
if (profileSystemServer) {
parsedArgs.runtimeFlags |= Zygote.PROFILE_SYSTEM_SERVER;
}
/* Request to fork the system server process */
pid = Zygote.forkSystemServer(
parsedArgs.uid, parsedArgs.gid,
parsedArgs.gids,
parsedArgs.runtimeFlags,
null,
parsedArgs.permittedCapabilities,
parsedArgs.effectiveCapabilities);
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
}
/* For child process */
//启动system server子进程
if (pid == 0) {
if (hasSecondZygote(abiList)) {
waitForSecondaryZygote(socketName);
}
zygoteServer.closeServerSocket();
//处理system server 进程剩下的工作
return handleSystemServerProcess(parsedArgs);
}
return null;
}
static jint com_android_internal_os_Zygote_nativeForkSystemServer(
JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,
jint runtime_flags, jobjectArray rlimits, jlong permittedCapabilities,
jlong effectiveCapabilities) {
pid_t pid = ForkAndSpecializeCommon(env, uid, gid, gids,
runtime_flags, rlimits,
permittedCapabilities, effectiveCapabilities,
MOUNT_EXTERNAL_DEFAULT, NULL, NULL, true, NULL,
NULL, false, NULL, NULL);
if (pid > 0) {
// The zygote process checks whether the child process has died or not.
//Zygote 经常检查子进程是否死亡
ALOGI("System server process %d has been created", pid);
gSystemServerPid = pid;
// There is a slight window that the system server process has crashed
// but it went unnoticed because we haven't published its pid yet. So
// we recheck here just to make sure that all is well.
//这有个system server已经奔溃的小窗口,但是它不通知,因为我们还没有发布它的pid,所以我们在这里重新检查确认好。
int status;
if (waitpid(pid, &status, WNOHANG) == pid) {
ALOGE("System server process %d has died. Restarting Zygote!", pid);
//当system server挂了,重启Zygote进程
RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
}
bool low_ram_device = GetBoolProperty("ro.config.low_ram", false);
bool per_app_memcg = GetBoolProperty("ro.config.per_app_memcg", low_ram_device);
if (per_app_memcg) {
// Assign system_server to the correct memory cgroup.
// Not all devices mount /dev/memcg so check for the file first
// to avoid unnecessarily printing errors and denials in the logs.
if (!access("/dev/memcg/system/tasks", F_OK) &&
!WriteStringToFile(StringPrintf("%d", pid), "/dev/memcg/system/tasks")) {
......
}
}
}
return pid;
}
// Utility routine to fork zygote and specialize the child process.
static pid_t ForkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
jint runtime_flags, jobjectArray javaRlimits,
jlong permittedCapabilities, jlong effectiveCapabilities,
jint mount_external,
jstring java_se_info, jstring java_se_name,
bool is_system_server, jintArray fdsToClose,
jintArray fdsToIgnore, bool is_child_zygote,
jstring instructionSet, jstring dataDir) {
//设置子进程的signal信号处理函数
SetSignalHandlers();
......
//fork pid
pid_t pid = fork();
if (pid == 0) {
//预初始化App
PreApplicationInit();
// Clean up any descriptors which must be closed immediately
//关闭并清除文件描述符
if (!DetachDescriptors(env, fdsToClose, &error_msg)) {
fail_fn(error_msg);
}
......
// If this zygote isn't root, it won't be able to create a process group,
// since the directory is owned by root.
if (!is_system_server && getuid() == 0) {
//对于非system_server子进程,则创建进程组
int rc = createProcessGroup(uid, getpid());
......
}
//设置resg id
int rc = setresgid(gid, gid, gid);
......
//设置res user ID
rc = setresuid(uid, uid, uid);
......
// Make it easier to debug audit logs by setting the main thread's name to the
// nice name rather than "app_process".
if (se_name_c_str == NULL && is_system_server) {
se_name_c_str = "system_server";
}
if (se_name_c_str != NULL) {
//设置线程名为system_server,方便调试
SetThreadName(se_name_c_str);
}
delete se_info;
delete se_name;
// Unset the SIGCHLD handler, but keep ignoring SIGHUP (rationale in SetSignalHandlers).
//设置子进程的signal信号处理函数为默认函数
UnsetChldSignalHandler();
//等价于调用zygote.callPostForkChildHooks()
env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, runtime_flags,
is_system_server, is_child_zygote, instructionSet);
......
} else if (pid > 0) {
// the parent process
//进入父进程,即zygote进程
......
}
}
return pid;
}
在这里,从Zygote进程fork 出一个进程用于创建system server进程,system server进程创建好后,便执行ZygoteInit.handleSystemServerProcess来处理system server剩下的工作;
这个方法主要做了以下处理:
/**
* Finish remaining work for the newly forked system server process.
*/
private static Runnable handleSystemServerProcess(ZygoteConnection.Arguments parsedArgs) {
// set umask to 0077 so new files and directories will default to owner-only permissions.
Os.umask(S_IRWXG | S_IRWXO);
if (parsedArgs.niceName != null) {
//设置当前进程名为"system_server"
Process.setArgV0(parsedArgs.niceName);
}
final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH");
if (systemServerClasspath != null) {
//执行dex优化操作
performSystemServerDexOpt(systemServerClasspath);
// Capturing profiles is only supported for debug or eng builds since selinux normally
// prevents it.
boolean profileSystemServer = SystemProperties.getBoolean(
"dalvik.vm.profilesystemserver", false);
if (profileSystemServer && (Build.IS_USERDEBUG || Build.IS_ENG)) {
try {
//准备system server配置
prepareSystemServerProfile(systemServerClasspath);
} catch (Exception e) {
Log.wtf(TAG, "Failed to set up system server profile", e);
}
}
}
if (parsedArgs.invokeWith != null) {
String[] args = parsedArgs.remainingArgs;
// If we have a non-null system server class path, we'll have to duplicate the
// existing arguments and append the classpath to it. ART will handle the classpath
//ART将处理现有的参数附加上classpath。
// correctly when we exec a new process.
if (systemServerClasspath != null) {
String[] amendedArgs = new String[args.length + 2];
amendedArgs[0] = "-cp";
amendedArgs[1] = systemServerClasspath;
System.arraycopy(args, 0, amendedArgs, 2, args.length);
args = amendedArgs;
}
//启动应用进程
WrapperInit.execApplication(parsedArgs.invokeWith,
parsedArgs.niceName, parsedArgs.targetSdkVersion,
VMRuntime.getCurrentInstructionSet(), null, args);
throw new IllegalStateException("Unexpected return from WrapperInit.execApplication");
} else {
ClassLoader cl = null;
if (systemServerClasspath != null) {
// 创建类加载器,并赋予当前线程
cl = createPathClassLoader(systemServerClasspath, parsedArgs.targetSdkVersion);
Thread.currentThread().setContextClassLoader(cl);
}
/*
* Pass the remaining arguments to SystemServer.
*/
//system_server故进入此分支
return ZygoteInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl);
}
}
public static final Runnable zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader) {
......
//重新打开android log中的System.out and System.err
RuntimeInit.redirectLogStreams();
//初始化时间、时区、HTTP User-agent格式,logmanager复位。
RuntimeInit.commonInit();
//zygote的初始化
ZygoteInit.nativeZygoteInit();
//应用的初始化
return RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader);
}
protected static final void commonInit() {
/*
* set handlers; these apply to all threads in the VM. Apps can replace
* the default handler, but not the pre handler.
*/
//设置未捕获异常handler
LoggingHandler loggingHandler = new LoggingHandler();
Thread.setUncaughtExceptionPreHandler(loggingHandler);
Thread.setDefaultUncaughtExceptionHandler(new KillApplicationHandler(loggingHandler));
/*
* Install a TimezoneGetter subclass for ZoneInfo.db
*/
//设置时区
TimezoneGetter.setInstance(new TimezoneGetter() {
@Override
public String getId() {
return SystemProperties.get("persist.sys.timezone");
}
});
TimeZone.setDefault(null);
/*
* Sets handler for java.util.logging to use Android log facilities.
* The odd "new instance-and-then-throw-away" is a mirror of how
* the "java.util.logging.config.class" system property works. We
* can't use the system property here since the logger has almost
* certainly already been initialized.
*/
LogManager.getLogManager().reset();
重置log
new AndroidConfig();
/*
* Sets the default HTTP User-Agent used by HttpURLConnection.
*/
设置userAgent格式
String userAgent = getDefaultUserAgent();
System.setProperty("http.agent", userAgent);
/*
* Wire socket tagging to traffic stats.
*/
// 设置socket的tag,用于网络流量统计
NetworkManagementSocketTagger.install();
......
initialized = true;
}
virtual void onZygoteInit()
{
sp proc = ProcessState::self();
ALOGV("App process: starting thread pool.\n");
//启动binder线程池
proc->startThreadPool();
}
void ProcessState::startThreadPool()
{
AutoMutex _l(mLock);
if (!mThreadPoolStarted) {
mThreadPoolStarted = true;
if (mSpawnThreadOnStart) {
//生成主线程
spawnPooledThread(true);
}
}
}
void ProcessState::spawnPooledThread(bool isMain)
{
if (mThreadPoolStarted) {
String8 name = makeBinderThreadName();
ALOGV("Spawning new pooled thread, name=%s\n", name.string());
//创建线程实例对象
sp t = new PoolThread(isMain);
//线程T 执行run。
t->run(name.string());
}
}
protected static Runnable applicationInit(int targetSdkVersion, String[] argv,
ClassLoader classLoader) {
// If the application calls System.exit(), terminate the process
// immediately without running any shutdown hooks. It is not possible to
// shutdown an Android application gracefully. Among other things, the
// Android runtime shutdown hooks close the Binder driver, which can cause
// leftover running threads to crash before the process actually exits.
//true代表应用程序退出时不调用AppRuntime.onExit(),否则会在退出前调用
nativeSetExitWithoutCleanup(true);
// We want to be fairly aggressive about heap utilization, to avoid
// holding on to a lot of memory that isn't needed.
//设置虚拟机的内存利用率参数值为0.75
VMRuntime.getRuntime().setTargetHeapUtilization(0.75f);
VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion);
//解析参数
final Arguments args = new Arguments(argv);
// The end of of the RuntimeInit event (see #zygoteInit).
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
/*通过反射方法findStaticMain,调用startClass的static方法 main(), 此处args.startClass为”com.android.server.SystemServer”*/
// Remaining arguments are passed to the start class's static main
return findStaticMain(args.startClass, args.startArgs, classLoader);
}
public static void main(String[] args) {
//执行system server run 方法
new SystemServer().run();
}
private void run() {
try {
......
//当前时间如果小于1970年,就将当前时间设置为1970年
if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
Slog.w(TAG, "System clock is before 1970; setting to 1970.");
SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
}
//
// Default the timezone property to GMT if not set.
//默认时区从系统属性persist.sys.timezone获得
String timezoneProperty = SystemProperties.get("persist.sys.timezone");
if (timezoneProperty == null || timezoneProperty.isEmpty()) {
Slog.w(TAG, "Timezone not set; setting to GMT.");
//如果系统属性persist.sys.timezone是null的,就设置persist.sys.timezone默认值为GMT。
SystemProperties.set("persist.sys.timezone", "GMT");
}
......
//设置地区语言,语言,国家,地区
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通信阻塞就发出警告
Binder.setWarnOnBlocking(true);
// The system server should always load safe labels
//为system server增加安全标签
PackageItemInfo.setForceSafeLabels(true);
// Default to FULL within the system server.
//system server 全局sql默认全同步
SQLiteGlobal.sDefaultSyncMode = SQLiteGlobal.SYNC_MODE_FULL;
// Deactivate SQLiteCompatibilityWalFlags until settings provider is initialized
//SQL初始化好后才能使用
SQLiteCompatibilityWalFlags.init(null);
......
// 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 | xq oqi'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
//如果发生OTA,同步系统属性。
SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
// Mmmmmm... more memory!
//清除内存增长上限,因为启动过程需要很多内存空间
VMRuntime.getRuntime().clearGrowthLimit();
// The system server has to run all of the time, so it needs to be
// as efficient as possible with its memory usage.
//设置内存的可能有效使用率为0.8
VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
// 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
//默认是会进行stack trace 打包的。
Parcel.setStackTraceParceling(true);
// Ensure binder calls into the system always run at foreground priority.
//确保当前系统进程的binder调用,总是运行在前台优先级(foreground priority)
BinderInternal.disableBackgroundScheduling(true);
// Increase the number of binder threads in system_server
设置system server最大binder线程数量上限。
BinderInternal.setMaxThreads(sMaxBinderThreads);
// Prepare the main looper thread (this thread).
// 主线程looper就在当前线程运行
android.os.Process.setThreadPriority(
android.os.Process.THREAD_PRIORITY_FOREGROUND);
android.os.Process.setCanSelfBackground(false);
Looper.prepareMainLooper();
Looper.getMainLooper().setSlowLogThresholdMs(
SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);
// Initialize native services.
/加载android_servers.so库,该库包含的源码在frameworks/base/services/目录下
System.loadLibrary("android_servers");
// Check whether we failed to shut down last time we tried.
// This call may not return.
//检测上次关机过程是否失败,该方法可能不会返回
performPendingShutdown();
// Initialize the system context.
//创建system 上下文
createSystemContext();
// Create the system service manager.
//创建SystemServiceManager
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setStartInfo(mRuntimeRestart,
mRuntimeStartElapsedTime, mRuntimeStartUptime);
//将mSystemServiceManager添加到本地服务的成员sLocalServiceObjects
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
// Prepare the thread pool for init tasks that can be parallelized
//在system server init期间并行初始化 线程池;
SystemServerInitThreadPool.get();
} finally {
......
}
// Start services.
// 启动各种服务
try {
//启动引导服务
startBootstrapServices();
//启动核心服务
startCoreServices();
//启动其他服务
startOtherServices();
//SystemServerInitThreadPool关闭
SystemServerInitThreadPool.shutdown();
} catch (Throwable ex) {
throw ex;
} finally {
}
//严苛模式初始化配置
StrictMode.initVmDefaults(null);
......
// Loop forever.
//进入looper循环
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
private void performPendingShutdown() {
//获取关机活动属性
final String shutdownAction = SystemProperties.get(
ShutdownThread.SHUTDOWN_ACTION_PROPERTY, "");
if (shutdownAction != null && shutdownAction.length() > 0) {
boolean reboot = (shutdownAction.charAt(0) == '1');
final String reason;
//截取出关机原因
if (shutdownAction.length() > 1) {
reason = shutdownAction.substring(1, shutdownAction.length());
} else {
reason = null;
}
// If it's a pending reboot into recovery to apply an update,
// always make sure uncrypt gets executed properly when needed.
// If '/cache/recovery/block.map' hasn't been created, stop the
// reboot which will fail for sure, and get a chance to capture a
// bugreport when that's still feasible. (Bug: 26444951)
//
if (reason != null && reason.startsWith(PowerManager.REBOOT_RECOVERY_UPDATE)) {
File packageFile = new File(UNCRYPT_PACKAGE_FILE);
if (packageFile.exists()) {
String filename = null;
try {
filename = FileUtils.readTextFile(packageFile, 0, null);
} catch (IOException e) {
Slog.e(TAG, "Error reading uncrypt package file", e);
}
if (filename != null && filename.startsWith("/data")) {
if (!new File(BLOCK_MAP_FILE).exists()) {
Slog.e(TAG, "Can't find block map file, uncrypt failed or " +
"unexpected runtime restart?");
return;
}
}
}
}
//关机原因不为空并且不是REBOOT_RECOVERY_UPDATE就执行关机或者重启
Runnable runnable = new Runnable() {
@Override
public void run() {
synchronized (this) {
ShutdownThread.rebootOrShutdown(null, reboot, reason);
}
}
};
// ShutdownThread must run on a looper capable of displaying the UI.
Message msg = Message.obtain(UiThread.getHandler(), runnable);
msg.setAsynchronous(true);
UiThread.getHandler().sendMessage(msg);
}
}
private void createSystemContext() {
//创建上下文
ActivityThread activityThread = ActivityThread.systemMain();
mSystemContext = activityThread.getSystemContext();
mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
//设置默认主题
final Context systemUiContext = activityThread.getSystemUiContext();
systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
}
createSystemContext这个过程会创建对象有ActivityThread,Instrumentation, ContextImpl,LoadedApk,Application;
private void startBootstrapServices() {
//初始化系统配置实例对象
SystemServerInitThreadPool.get().submit(SystemConfig::getInstance, TAG_SYSTEM_CONFIG);
// MUST be very early
String ioCtlOpen = SystemProperties.get("persist.sys.ioctl.enable");
if (ioCtlOpen == null || ioCtlOpen.isEmpty()) {
SystemProperties.set("persist.sys.ioctl.enable", "true");
}
......
//阻塞等待与installd建立socket通道
Installer installer = mSystemServiceManager.startService(Installer.class);
......
//启动DeviceIdentifiersPolicyService
mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);
//启动ActivityManagerService
mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
//启动PowerManagerService
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
// Now that the power manager has been started, let the activity manager
// initialize power management features.
mActivityManagerService.initPowerManagement();
//启动RecoverySystemService
mSystemServiceManager.startService(RecoverySystemService.class);
//如果有循环重启就启动救援机制
RescueParty.noteBoot(mSystemContext);
//启动LightsService
mSystemServiceManager.startService(LightsService.class);
//启动DisplayManagerService
mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
//Phase100: 在初始化package manager之前,需要默认的显示.
mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
traceEnd();
//当设备正在加密时,仅运行核心
String cryptState = SystemProperties.get("vold.decrypt");
if (ENCRYPTING_STATE.equals(cryptState)) {
Slog.w(TAG, "Detected encryption in progress - only parsing core apps");
mOnlyCore = true;
} else if (ENCRYPTED_STATE.equals(cryptState)) {
Slog.w(TAG, "Device encrypted - only parsing core apps");
mOnlyCore = true;
}
//启动服务PackageManagerService
mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
mFirstBoot = mPackageManagerService.isFirstBoot();
mPackageManager = mSystemContext.getPackageManager();
if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
.......
}
//启动UserManagerService
mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
// Initialize attribute cache used to cache resources from packages.
//用应用的缓存资源初始化缓存参数
AttributeCache.init(mSystemContext);
mActivityManagerService.setSystemProcess();
// DisplayManagerService needs to setup android.display scheduling related policies
// since setSystemProcess() would have overridden policies due to setProcessGroup
//建立显示机制,setSystemProcess可以覆盖策略
mDisplayManagerService.setupSchedulerPolicies();
// Manages Overlay packages
//管理overlay 包
OverlayManagerService overlayManagerService = new OverlayManagerService(
mSystemContext, installer);
mSystemServiceManager.startService(overlayManagerService);
if (SystemProperties.getInt("persist.sys.displayinset.top", 0) > 0) {
// DisplayManager needs the overlay immediately.
//需要叠加显示
overlayManagerService.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.
// Start sensor service in a separate thread. Completion should be checked
// before using it.
//启动 sensor server
mSensorServiceStart = SystemServerInitThreadPool.get().submit(() -> {
startSensorService();
}, START_SENSOR_SERVICE);
}
private void startCoreServices() {
//启动电池服务
mSystemServiceManager.startService(BatteryService.class);
//启动流量统计服务
mSystemServiceManager.startService(UsageStatsService.class);
mActivityManagerService.setUsageStatsManager(
LocalServices.getService(UsageStatsManagerInternal.class));
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) {
//启动webview
mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
}
//启动BinderCallsStatsService
BinderCallsStatsService.start();
}
/**
* Starts a miscellaneous grab bag of stuff that has yet to be refactored
* and organized.
*/
private void startOtherServices() {
......
// For debugging RescueParty
//用于救援机制调试
if (Build.IS_DEBUGGABLE && SystemProperties.getBoolean("debug.crash_system", false)) {
throw new RuntimeException();
}
try {
final String SECONDARY_ZYGOTE_PRELOAD = "SecondaryZygotePreload";
//第二次Zygote proload
mZygotePreload = SystemServerInitThreadPool.get().submit(() -> {
try {
if (!Process.zygoteProcess.preloadDefault(Build.SUPPORTED_32_BIT_ABIS[0])) {
Slog.e(TAG, "Unable to preload default resources");
}
} catch (Exception ex) {
}
}, SECONDARY_ZYGOTE_PRELOAD);
//该服务根据UID提供应用描述信息。
ServiceManager.addService("sec_key_att_app_id_provider",
new KeyAttestationApplicationIdProviderService(context));
//该服务是替换KeyChain提供存储凭证的私钥。
mSystemServiceManager.startService(KeyChainSystemService.class);
//启动执行策略服务
ServiceManager.addService("scheduling_policy", new SchedulingPolicyService());
......
//resolver
mContentResolver = context.getContentResolver();
//provider
mActivityManagerService.installSystemProviders();
// Now that SettingsProvider is ready, reactivate SQLiteCompatibilityWalFlags
SQLiteCompatibilityWalFlags.reset();
traceEnd();
// Records errors and logs, for example wtf()
// Currently this service indirectly depends on SettingsProvider so do this after
// InstallSystemProviders.
traceBeginAndSlog("StartDropBoxManager");
mSystemServiceManager.startService(DropBoxManagerService.class);
traceEnd();
traceBeginAndSlog("StartVibratorService");
vibrator = new VibratorService(context);
ServiceManager.addService("vibrator", vibrator);
traceEnd();
if (!isWatch) {
traceBeginAndSlog("StartConsumerIrService");
consumerIr = new ConsumerIrService(context);
ServiceManager.addService(Context.CONSUMER_IR_SERVICE, consumerIr);
traceEnd();
}
traceBeginAndSlog("StartAlarmManagerService");
mSystemServiceManager.startService(AlarmManagerService.class);
traceEnd();
traceBeginAndSlog("InitWatchdog");
final Watchdog watchdog = Watchdog.getInstance();
watchdog.init(context, mActivityManagerService);
traceEnd();
traceBeginAndSlog("StartInputManagerService");
inputManager = new InputManagerService(context);
traceEnd();
traceBeginAndSlog("StartWindowManagerService");
// WMS needs sensor service ready
ConcurrentUtils.waitForFutureNoInterrupt(mSensorServiceStart, START_SENSOR_SERVICE);
mSensorServiceStart = null;
wm = WindowManagerService.main(context, inputManager,
mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL,
!mFirstBoot, mOnlyCore, new PhoneWindowManager());
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);
traceEnd();
traceBeginAndSlog("SetWindowManagerService");
mActivityManagerService.setWindowManager(wm);
traceEnd();
traceBeginAndSlog("WindowManagerServiceOnInitReady");
wm.onInitReady();
traceEnd();
// Start receiving calls from HIDL services. Start in in a separate thread
// because it need to connect to SensorManager. This have to start
// after START_SENSOR_SERVICE is done.
SystemServerInitThreadPool.get().submit(() -> {
TimingsTraceLog traceLog = new TimingsTraceLog(
SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
traceLog.traceBegin(START_HIDL_SERVICES);
startHidlServices();
traceLog.traceEnd();
}, START_HIDL_SERVICES);
if (!isWatch && enableVrService) {
traceBeginAndSlog("StartVrManagerService");
mSystemServiceManager.startService(VrManagerService.class);
traceEnd();
}
traceBeginAndSlog("StartInputManager");
inputManager.setWindowManagerCallbacks(wm.getInputMonitor());
inputManager.start();
traceEnd();
// TODO: Use service dependencies instead.
traceBeginAndSlog("DisplayManagerWindowManagerAndInputReady");
mDisplayManagerService.windowManagerAndInputReady();
traceEnd();
// Skip Bluetooth if we have an emulator kernel
// TODO: Use a more reliable check to see if this product should
// support Bluetooth - see bug 988521
if (isEmulator) {
Slog.i(TAG, "No Bluetooth Service (emulator)");
} else 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 {
traceBeginAndSlog("StartBluetoothService");
mSystemServiceManager.startService(BluetoothService.class);
traceEnd();
}
traceBeginAndSlog("IpConnectivityMetrics");
mSystemServiceManager.startService(IpConnectivityMetrics.class);
traceEnd();
traceBeginAndSlog("NetworkWatchlistService");
mSystemServiceManager.startService(NetworkWatchlistService.Lifecycle.class);
traceEnd();
traceBeginAndSlog("PinnerService");
mSystemServiceManager.startService(PinnerService.class);
traceEnd();
} catch (RuntimeException e) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting core service", e);
}
StatusBarManagerService statusBar = null;
INotificationManager notification = null;
LocationManagerService location = null;
CountryDetectorService countryDetector = null;
ILockSettings lockSettings = null;
MediaRouterService mediaRouter = null;
// Bring up services needed for UI.
if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
traceBeginAndSlog("StartInputMethodManagerLifecycle");
mSystemServiceManager.startService(InputMethodManagerService.Lifecycle.class);
traceEnd();
traceBeginAndSlog("StartAccessibilityManagerService");
try {
ServiceManager.addService(Context.ACCESSIBILITY_SERVICE,
new AccessibilityManagerService(context));
} catch (Throwable e) {
reportWtf("starting Accessibility Manager", e);
}
traceEnd();
}
traceBeginAndSlog("MakeDisplayReady");
try {
wm.displayReady();
} catch (Throwable e) {
reportWtf("making display ready", e);
}
traceEnd();
if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
if (!"0".equals(SystemProperties.get("system_init.startmountservice"))) {
traceBeginAndSlog("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);
}
traceEnd();
traceBeginAndSlog("StartStorageStatsService");
try {
mSystemServiceManager.startService(STORAGE_STATS_SERVICE_CLASS);
} catch (Throwable e) {
reportWtf("starting StorageStatsService", e);
}
traceEnd();
}
}
// We start this here so that we update our configuration to set watch or television
// as appropriate.
traceBeginAndSlog("StartUiModeManager");
mSystemServiceManager.startService(UiModeManagerService.class);
traceEnd();
if (!mOnlyCore) {
traceBeginAndSlog("UpdatePackagesIfNeeded");
try {
mPackageManagerService.updatePackagesIfNeeded();
} catch (Throwable e) {
reportWtf("update packages", e);
}
traceEnd();
}
traceBeginAndSlog("PerformFstrimIfNeeded");
try {
mPackageManagerService.performFstrimIfNeeded();
} catch (Throwable e) {
reportWtf("performing fstrim", e);
}
traceEnd();
if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
traceBeginAndSlog("StartOvumOvulationService");
try {
mOvumOvulationService = mSystemServiceManager.startService(OvumOvulationService.class);
mOvumOvulationService.setActivityManager(mActivityManagerService);
} catch (Throwable e) {
reportWtf("starting OvumOvulationService", e);
}
traceEnd();
traceBeginAndSlog("StartLockSettingsService");
try {
mSystemServiceManager.startService(LOCK_SETTINGS_SERVICE_CLASS);
lockSettings = ILockSettings.Stub.asInterface(
ServiceManager.getService("lock_settings"));
} catch (Throwable e) {
reportWtf("starting LockSettingsService service", e);
}
traceEnd();
final boolean hasPdb = !SystemProperties.get(PERSISTENT_DATA_BLOCK_PROP).equals("");
if (hasPdb) {
traceBeginAndSlog("StartPersistentDataBlock");
mSystemServiceManager.startService(PersistentDataBlockService.class);
traceEnd();
}
if (hasPdb || OemLockService.isHalPresent()) {
// Implementation depends on pdb or the OemLock HAL
traceBeginAndSlog("StartOemLockService");
mSystemServiceManager.startService(OemLockService.class);
traceEnd();
}
traceBeginAndSlog("StartDeviceIdleController");
mSystemServiceManager.startService(DeviceIdleController.class);
traceEnd();
// Always start the Device Policy Manager, so that the API is compatible with
// API8.
traceBeginAndSlog("StartDevicePolicyManager");
mSystemServiceManager.startService(DevicePolicyManagerService.Lifecycle.class);
traceEnd();
if (!isWatch) {
traceBeginAndSlog("StartStatusBarManagerService");
try {
statusBar = new StatusBarManagerService(context, wm);
ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar);
} catch (Throwable e) {
reportWtf("starting StatusBarManagerService", e);
}
traceEnd();
}
traceBeginAndSlog("StartClipboardService");
mSystemServiceManager.startService(ClipboardService.class);
traceEnd();
traceBeginAndSlog("StartNetworkManagementService");
try {
networkManagement = NetworkManagementService.create(context);
ServiceManager.addService(Context.NETWORKMANAGEMENT_SERVICE, networkManagement);
} catch (Throwable e) {
reportWtf("starting NetworkManagement Service", e);
}
traceEnd();
traceBeginAndSlog("StartIpSecService");
try {
ipSecService = IpSecService.create(context);
ServiceManager.addService(Context.IPSEC_SERVICE, ipSecService);
} catch (Throwable e) {
reportWtf("starting IpSec Service", e);
}
traceEnd();
traceBeginAndSlog("StartTextServicesManager");
mSystemServiceManager.startService(TextServicesManagerService.Lifecycle.class);
traceEnd();
if (!disableSystemTextClassifier) {
traceBeginAndSlog("StartTextClassificationManagerService");
mSystemServiceManager.startService(TextClassificationManagerService.Lifecycle.class);
traceEnd();
}
traceBeginAndSlog("StartNetworkScoreService");
mSystemServiceManager.startService(NetworkScoreService.Lifecycle.class);
traceEnd();
traceBeginAndSlog("StartNetworkStatsService");
try {
networkStats = NetworkStatsService.create(context, networkManagement);
ServiceManager.addService(Context.NETWORK_STATS_SERVICE, networkStats);
} catch (Throwable e) {
reportWtf("starting NetworkStats Service", e);
}
traceEnd();
traceBeginAndSlog("StartNetworkPolicyManagerService");
try {
networkPolicy = new NetworkPolicyManagerService(context, mActivityManagerService,
networkManagement);
ServiceManager.addService(Context.NETWORK_POLICY_SERVICE, networkPolicy);
} catch (Throwable e) {
reportWtf("starting NetworkPolicy Service", e);
}
traceEnd();
if (!mOnlyCore) {
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_WIFI)) {
// Wifi Service must be started first for wifi-related services.
traceBeginAndSlog("StartWifi");
mSystemServiceManager.startService(WIFI_SERVICE_CLASS);
traceEnd();
traceBeginAndSlog("StartWifiScanning");
mSystemServiceManager.startService(
"com.android.server.wifi.scanner.WifiScanningService");
traceEnd();
}
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_WIFI_RTT)) {
traceBeginAndSlog("StartRttService");
mSystemServiceManager.startService(
"com.android.server.wifi.rtt.RttService");
traceEnd();
}
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_WIFI_AWARE)) {
traceBeginAndSlog("StartWifiAware");
mSystemServiceManager.startService(WIFI_AWARE_SERVICE_CLASS);
traceEnd();
}
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_WIFI_DIRECT)) {
traceBeginAndSlog("StartWifiP2P");
mSystemServiceManager.startService(WIFI_P2P_SERVICE_CLASS);
traceEnd();
}
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_LOWPAN)) {
traceBeginAndSlog("StartLowpan");
mSystemServiceManager.startService(LOWPAN_SERVICE_CLASS);
traceEnd();
}
}
if (enableWigig) {
try {
Slog.i(TAG, "Wigig Service");
String wigigClassPath =
"/system/framework/wigig-service.jar" + ":" +
"/system/framework/vendor.qti.hardware.wigig.supptunnel-V1.0-java.jar" + ":" +
"/system/framework/vendor.qti.hardware.wigig.netperftuner-V1.0-java.jar";
PathClassLoader wigigClassLoader =
new PathClassLoader(wigigClassPath, getClass().getClassLoader());
Class wigigP2pClass = wigigClassLoader.loadClass(
"com.qualcomm.qti.server.wigig.p2p.WigigP2pServiceImpl");
Constructor ctor = wigigP2pClass.getConstructor(Context.class);
wigigP2pService = ctor.newInstance(context);
Slog.i(TAG, "Successfully loaded WigigP2pServiceImpl class");
ServiceManager.addService("wigigp2p", (IBinder) wigigP2pService);
Class wigigClass = wigigClassLoader.loadClass(
"com.qualcomm.qti.server.wigig.WigigService");
ctor = wigigClass.getConstructor(Context.class);
wigigService = ctor.newInstance(context);
Slog.i(TAG, "Successfully loaded WigigService class");
ServiceManager.addService("wigig", (IBinder) wigigService);
} catch (Throwable e) {
reportWtf("starting WigigService", e);
}
}
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_ETHERNET) ||
mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_HOST)) {
traceBeginAndSlog("StartEthernet");
mSystemServiceManager.startService(ETHERNET_SERVICE_CLASS);
traceEnd();
}
traceBeginAndSlog("StartConnectivityService");
try {
connectivity = new ConnectivityService(
context, networkManagement, networkStats, networkPolicy);
ServiceManager.addService(Context.CONNECTIVITY_SERVICE, connectivity,
/* allowIsolated= */ false,
DUMP_FLAG_PRIORITY_HIGH | DUMP_FLAG_PRIORITY_NORMAL);
networkStats.bindConnectivityManager(connectivity);
networkPolicy.bindConnectivityManager(connectivity);
} catch (Throwable e) {
reportWtf("starting Connectivity Service", e);
}
traceEnd();
traceBeginAndSlog("StartNsdService");
try {
serviceDiscovery = NsdService.create(context);
ServiceManager.addService(
Context.NSD_SERVICE, serviceDiscovery);
} catch (Throwable e) {
reportWtf("starting Service Discovery Service", e);
}
traceEnd();
traceBeginAndSlog("StartSystemUpdateManagerService");
try {
ServiceManager.addService(Context.SYSTEM_UPDATE_SERVICE,
new SystemUpdateManagerService(context));
} catch (Throwable e) {
reportWtf("starting SystemUpdateManagerService", e);
}
traceEnd();
traceBeginAndSlog("StartUpdateLockService");
try {
ServiceManager.addService(Context.UPDATE_LOCK_SERVICE,
new UpdateLockService(context));
} catch (Throwable e) {
reportWtf("starting UpdateLockService", e);
}
traceEnd();
traceBeginAndSlog("StartNotificationManager");
mSystemServiceManager.startService(NotificationManagerService.class);
SystemNotificationChannels.createAll(context);
notification = INotificationManager.Stub.asInterface(
ServiceManager.getService(Context.NOTIFICATION_SERVICE));
traceEnd();
traceBeginAndSlog("StartDeviceMonitor");
mSystemServiceManager.startService(DeviceStorageMonitorService.class);
traceEnd();
traceBeginAndSlog("StartLocationManagerService");
try {
location = new LocationManagerService(context);
ServiceManager.addService(Context.LOCATION_SERVICE, location);
} catch (Throwable e) {
reportWtf("starting Location Manager", e);
}
traceEnd();
traceBeginAndSlog("StartCountryDetectorService");
try {
countryDetector = new CountryDetectorService(context);
ServiceManager.addService(Context.COUNTRY_DETECTOR, countryDetector);
} catch (Throwable e) {
reportWtf("starting Country Detector", e);
}
traceEnd();
traceBeginAndSlog("StartOvumManagerService");
try {
ServiceManager.addService(Context.OVUM_MANAGER_SERVICE,
new OvumManagerService(context, mPowerManagerService, mActivityManagerService));
} catch (Throwable e) {
reportWtf("starting OvumManagerService", e);
}
traceEnd();
traceBeginAndSlog("StartFreezeService");
try {
if (FreezeManager.isFreezeOpen()) {
ServiceManager.addService(Context.OVUM_FREEZE_SERVICE,
new FreezeService(context, mActivityManagerService, location));
}
} catch (Throwable e) {
reportWtf("starting FreezeService", e);
}
traceEnd();
try {
ServiceManager.addService(Context.OVUM_PERFORMANCEOBSERVER_SERVICE,
new PerformanceObserverService(context, mActivityManagerService));
} catch (Throwable e) {
reportWtf("starting PerformanceObserverService", e);
}
/* try {
ServiceManager.addService(Context.PERFORMANCE_MONITOR_SERVICE,
new PerformanceObserverService(context, mActivityManagerService));
} catch (Throwable e) {
reportWtf("starting PerformanceMonitor", e);
}
*/
if (!isWatch) {
traceBeginAndSlog("StartSearchManagerService");
try {
mSystemServiceManager.startService(SEARCH_MANAGER_SERVICE_CLASS);
} catch (Throwable e) {
reportWtf("starting Search Service", e);
}
traceEnd();
}
if (context.getResources().getBoolean(R.bool.config_enableWallpaperService)) {
traceBeginAndSlog("StartWallpaperManagerService");
mSystemServiceManager.startService(WALLPAPER_SERVICE_CLASS);
traceEnd();
}
traceBeginAndSlog("StartAudioService");
mSystemServiceManager.startService(AudioService.Lifecycle.class);
traceEnd();
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_BROADCAST_RADIO)) {
traceBeginAndSlog("StartBroadcastRadioService");
mSystemServiceManager.startService(BroadcastRadioService.class);
traceEnd();
}
traceBeginAndSlog("StartDockObserver");
mSystemServiceManager.startService(DockObserver.class);
traceEnd();
if (isWatch) {
traceBeginAndSlog("StartThermalObserver");
mSystemServiceManager.startService(THERMAL_OBSERVER_CLASS);
traceEnd();
}
traceBeginAndSlog("StartWiredAccessoryManager");
try {
// Listen for wired headset changes
inputManager.setWiredAccessoryCallbacks(
new WiredAccessoryManager(context, inputManager));
} catch (Throwable e) {
reportWtf("starting WiredAccessoryManager", e);
}
traceEnd();
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_MIDI)) {
// Start MIDI Manager service
traceBeginAndSlog("StartMidiManager");
mSystemServiceManager.startService(MIDI_SERVICE_CLASS);
traceEnd();
}
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_HOST)
|| mPackageManager.hasSystemFeature(
PackageManager.FEATURE_USB_ACCESSORY)
|| isEmulator) {
// Manage USB host and device support
traceBeginAndSlog("StartUsbService");
mSystemServiceManager.startService(USB_SERVICE_CLASS);
traceEnd();
}
if (!isWatch) {
traceBeginAndSlog("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);
}
traceEnd();
}
traceBeginAndSlog("StartHardwarePropertiesManagerService");
try {
hardwarePropertiesService = new HardwarePropertiesManagerService(context);
ServiceManager.addService(Context.HARDWARE_PROPERTIES_SERVICE,
hardwarePropertiesService);
} catch (Throwable e) {
Slog.e(TAG, "Failure starting HardwarePropertiesManagerService", e);
}
traceEnd();
traceBeginAndSlog("StartTwilightService");
mSystemServiceManager.startService(TwilightService.class);
traceEnd();
if (ColorDisplayController.isAvailable(context)) {
traceBeginAndSlog("StartNightDisplay");
mSystemServiceManager.startService(ColorDisplayService.class);
traceEnd();
}
traceBeginAndSlog("StartJobScheduler");
JobSchedulerService js = mSystemServiceManager.startService(JobSchedulerService.class);
traceEnd();
traceBeginAndSlog("StartIdleControllerService");
try {
ServiceManager.addService(Context.OVUM_IDLE_CONTROLLER_SERVICE,
new IdleControllerService(context, mPowerManagerService, mActivityManagerService, location, wm, js));
} catch (Throwable e) {
reportWtf("starting IdleControllerService", e);
}
traceEnd();
traceBeginAndSlog("StartSoundTrigger");
mSystemServiceManager.startService(SoundTriggerService.class);
traceEnd();
traceBeginAndSlog("StartTrustManager");
mSystemServiceManager.startService(TrustManagerService.class);
traceEnd();
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_BACKUP)) {
traceBeginAndSlog("StartBackupManager");
mSystemServiceManager.startService(BACKUP_MANAGER_SERVICE_CLASS);
traceEnd();
}
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_APP_WIDGETS)
|| context.getResources().getBoolean(R.bool.config_enableAppWidgetService)) {
traceBeginAndSlog("StartAppWidgerService");
mSystemServiceManager.startService(APPWIDGET_SERVICE_CLASS);
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.
traceBeginAndSlog("StartVoiceRecognitionManager");
mSystemServiceManager.startService(VOICE_RECOGNITION_MANAGER_SERVICE_CLASS);
traceEnd();
if (GestureLauncherService.isGestureLauncherEnabled(context.getResources())) {
traceBeginAndSlog("StartGestureLauncher");
mSystemServiceManager.startService(GestureLauncherService.class);
traceEnd();
}
traceBeginAndSlog("StartSensorNotification");
mSystemServiceManager.startService(SensorNotificationService.class);
traceEnd();
traceBeginAndSlog("StartContextHubSystemService");
mSystemServiceManager.startService(ContextHubSystemService.class);
traceEnd();
traceBeginAndSlog("StartDiskStatsService");
try {
ServiceManager.addService("diskstats", new DiskStatsService(context));
} catch (Throwable e) {
reportWtf("starting DiskStats Service", e);
}
traceEnd();
// timezone.RulesManagerService will prevent a device starting up if the chain of trust
// required for safe time zone updates might be broken. RuleManagerService cannot do
// this check when mOnlyCore == true, so we don't enable the service in this case.
// This service requires that JobSchedulerService is already started when it starts.
final boolean startRulesManagerService =
!mOnlyCore && context.getResources().getBoolean(
R.bool.config_enableUpdateableTimeZoneRules);
if (startRulesManagerService) {
traceBeginAndSlog("StartTimeZoneRulesManagerService");
mSystemServiceManager.startService(TIME_ZONE_RULES_MANAGER_SERVICE_CLASS);
traceEnd();
}
if (!isWatch) {
traceBeginAndSlog("StartNetworkTimeUpdateService");
try {
networkTimeUpdater = new NetworkTimeUpdateService(context);
ServiceManager.addService("network_time_update_service", networkTimeUpdater);
} catch (Throwable e) {
reportWtf("starting NetworkTimeUpdate service", e);
}
traceEnd();
}
traceBeginAndSlog("StartCommonTimeManagementService");
try {
commonTimeMgmtService = new CommonTimeManagementService(context);
ServiceManager.addService("commontime_management", commonTimeMgmtService);
} catch (Throwable e) {
reportWtf("starting CommonTimeManagementService service", e);
}
traceEnd();
traceBeginAndSlog("CertBlacklister");
try {
CertBlacklister blacklister = new CertBlacklister(context);
} catch (Throwable e) {
reportWtf("starting CertBlacklister", e);
}
traceEnd();
if (EmergencyAffordanceManager.ENABLED) {
// EmergencyMode service
traceBeginAndSlog("StartEmergencyAffordanceService");
mSystemServiceManager.startService(EmergencyAffordanceService.class);
traceEnd();
}
// Dreams (interactive idle-time views, a/k/a screen savers, and doze mode)
traceBeginAndSlog("StartDreamManager");
mSystemServiceManager.startService(DreamManagerService.class);
traceEnd();
traceBeginAndSlog("AddGraphicsStatsService");
ServiceManager.addService(GraphicsStatsService.GRAPHICS_STATS_SERVICE,
new GraphicsStatsService(context));
traceEnd();
if (CoverageService.ENABLED) {
traceBeginAndSlog("AddCoverageService");
ServiceManager.addService(CoverageService.COVERAGE_SERVICE, new CoverageService());
traceEnd();
}
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_PRINTING)) {
traceBeginAndSlog("StartPrintManager");
mSystemServiceManager.startService(PRINT_MANAGER_SERVICE_CLASS);
traceEnd();
}
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_COMPANION_DEVICE_SETUP)) {
traceBeginAndSlog("StartCompanionDeviceManager");
mSystemServiceManager.startService(COMPANION_DEVICE_MANAGER_SERVICE_CLASS);
traceEnd();
}
traceBeginAndSlog("StartRestrictionManager");
mSystemServiceManager.startService(RestrictionsManagerService.class);
traceEnd();
traceBeginAndSlog("StartMediaSessionService");
mSystemServiceManager.startService(MediaSessionService.class);
traceEnd();
traceBeginAndSlog("StartMediaUpdateService");
mSystemServiceManager.startService(MediaUpdateService.class);
traceEnd();
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_HDMI_CEC)) {
traceBeginAndSlog("StartHdmiControlService");
mSystemServiceManager.startService(HdmiControlService.class);
traceEnd();
}
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_LIVE_TV)
|| mPackageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)) {
traceBeginAndSlog("StartTvInputManager");
mSystemServiceManager.startService(TvInputManagerService.class);
traceEnd();
}
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)) {
traceBeginAndSlog("StartMediaResourceMonitor");
mSystemServiceManager.startService(MediaResourceMonitorService.class);
traceEnd();
}
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)) {
traceBeginAndSlog("StartTvRemoteService");
mSystemServiceManager.startService(TvRemoteService.class);
traceEnd();
}
traceBeginAndSlog("StartMediaRouterService");
try {
mediaRouter = new MediaRouterService(context);
ServiceManager.addService(Context.MEDIA_ROUTER_SERVICE, mediaRouter);
} catch (Throwable e) {
reportWtf("starting MediaRouterService", e);
}
traceEnd();
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {
traceBeginAndSlog("StartFingerprintSensor");
mSystemServiceManager.startService(FingerprintService.class);
traceEnd();
}
traceBeginAndSlog("StartBackgroundDexOptService");
try {
BackgroundDexOptService.schedule(context);
} catch (Throwable e) {
reportWtf("starting StartBackgroundDexOptService", e);
}
traceEnd();
traceBeginAndSlog("StartPruneInstantAppsJobService");
try {
PruneInstantAppsJobService.schedule(context);
} catch (Throwable e) {
reportWtf("StartPruneInstantAppsJobService", e);
}
traceEnd();
// LauncherAppsService uses ShortcutService.
traceBeginAndSlog("StartShortcutServiceLifecycle");
mSystemServiceManager.startService(ShortcutService.Lifecycle.class);
traceEnd();
traceBeginAndSlog("StartLauncherAppsService");
mSystemServiceManager.startService(LauncherAppsService.class);
traceEnd();
traceBeginAndSlog("StartCrossProfileAppsService");
mSystemServiceManager.startService(CrossProfileAppsService.class);
traceEnd();
}
if (!isWatch) {
traceBeginAndSlog("StartMediaProjectionManager");
mSystemServiceManager.startService(MediaProjectionManagerService.class);
traceEnd();
}
if (isWatch) {
traceBeginAndSlog("StartWearConfigService");
mSystemServiceManager.startService(WEAR_CONFIG_SERVICE_CLASS);
traceEnd();
traceBeginAndSlog("StartWearConnectivityService");
mSystemServiceManager.startService(WEAR_CONNECTIVITY_SERVICE_CLASS);
traceEnd();
traceBeginAndSlog("StartWearTimeService");
mSystemServiceManager.startService(WEAR_DISPLAY_SERVICE_CLASS);
mSystemServiceManager.startService(WEAR_TIME_SERVICE_CLASS);
traceEnd();
if (enableLeftyService) {
traceBeginAndSlog("StartWearLeftyService");
mSystemServiceManager.startService(WEAR_LEFTY_SERVICE_CLASS);
traceEnd();
}
traceBeginAndSlog("StartWearGlobalActionsService");
mSystemServiceManager.startService(WEAR_GLOBAL_ACTIONS_SERVICE_CLASS);
traceEnd();
}
if (!disableSlices) {
traceBeginAndSlog("StartSliceManagerService");
mSystemServiceManager.startService(SLICE_MANAGER_SERVICE_CLASS);
traceEnd();
}
if (!disableCameraService) {
traceBeginAndSlog("StartCameraServiceProxy");
mSystemServiceManager.startService(CameraServiceProxy.class);
traceEnd();
}
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_EMBEDDED)) {
traceBeginAndSlog("StartIoTSystemService");
mSystemServiceManager.startService(IOT_SERVICE_CLASS);
traceEnd();
}
// Statsd helper
traceBeginAndSlog("StartStatsCompanionService");
mSystemServiceManager.startService(StatsCompanionService.Lifecycle.class);
traceEnd();
// Before things start rolling, be sure we have decided whether
// we are in safe mode.
final boolean safeMode = wm.detectSafeMode();
if (safeMode) {
traceBeginAndSlog("EnterSafeModeAndDisableJitCompilation");
mActivityManagerService.enterSafeMode();
// Disable the JIT for the system_server process
VMRuntime.getRuntime().disableJitCompilation();
traceEnd();
} else {
// Enable the JIT for the system_server process
traceBeginAndSlog("StartJitCompilation");
VMRuntime.getRuntime().startJitCompilation();
traceEnd();
}
// MMS service broker
traceBeginAndSlog("StartMmsService");
mmsService = mSystemServiceManager.startService(MmsServiceBroker.class);
traceEnd();
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOFILL)) {
traceBeginAndSlog("StartAutoFillService");
mSystemServiceManager.startService(AUTO_FILL_MANAGER_SERVICE_CLASS);
traceEnd();
}
// It is now time to start up the app processes...
traceBeginAndSlog("MakeVibratorServiceReady");
try {
vibrator.systemReady();
} catch (Throwable e) {
reportWtf("making Vibrator Service ready", e);
}
traceEnd();
traceBeginAndSlog("MakeLockSettingsServiceReady");
if (lockSettings != null) {
try {
lockSettings.systemReady();
} catch (Throwable e) {
reportWtf("making Lock Settings Service ready", e);
}
}
traceEnd();
// Needed by DevicePolicyManager for initialization
traceBeginAndSlog("StartBootPhaseLockSettingsReady");
mSystemServiceManager.startBootPhase(SystemService.PHASE_LOCK_SETTINGS_READY);
traceEnd();
traceBeginAndSlog("StartBootPhaseSystemServicesReady");
mSystemServiceManager.startBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);
traceEnd();
// Wigig services are not registered as system services because of class loader
// limitations, send boot phase notification separately
if (enableWigig) {
try {
Slog.i(TAG, "calling onBootPhase for Wigig Services");
Class wigigP2pClass = wigigP2pService.getClass();
Method m = wigigP2pClass.getMethod("onBootPhase", int.class);
m.invoke(wigigP2pService, new Integer(
SystemService.PHASE_SYSTEM_SERVICES_READY));
Class wigigClass = wigigService.getClass();
m = wigigClass.getMethod("onBootPhase", int.class);
m.invoke(wigigService, new Integer(
SystemService.PHASE_SYSTEM_SERVICES_READY));
} catch (Throwable e) {
reportWtf("Wigig services ready", e);
}
}
traceBeginAndSlog("MakeWindowManagerServiceReady");
try {
wm.systemReady();
} catch (Throwable e) {
reportWtf("making Window Manager Service ready", e);
}
traceEnd();
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();
WindowManager w = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
w.getDefaultDisplay().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();
}
traceBeginAndSlog("MakePowerManagerServiceReady");
try {
// TODO: use boot phase
mPowerManagerService.systemReady(mActivityManagerService.getAppOpsService());
} catch (Throwable e) {
reportWtf("making Power Manager Service ready", e);
}
traceEnd();
traceBeginAndSlog("MakePackageManagerServiceReady");
mPackageManagerService.systemReady();
traceEnd();
traceBeginAndSlog("MakeDisplayManagerServiceReady");
try {
// TODO: use boot phase and communicate these flags some other way
mDisplayManagerService.systemReady(safeMode, mOnlyCore);
} catch (Throwable e) {
reportWtf("making Display Manager Service ready", e);
}
traceEnd();
mSystemServiceManager.setSafeMode(safeMode);
// Start device specific services
traceBeginAndSlog("StartDeviceSpecificServices");
final String[] classes = mSystemContext.getResources().getStringArray(
R.array.config_deviceSpecificSystemServices);
for (final String className : classes) {
traceBeginAndSlog("StartDeviceSpecificServices " + className);
try {
mSystemServiceManager.startService(className);
} catch (Throwable e) {
reportWtf("starting " + className, e);
}
traceEnd();
}
traceEnd();
traceBeginAndSlog("StartBootPhaseDeviceSpecificServicesReady");
mSystemServiceManager.startBootPhase(SystemService.PHASE_DEVICE_SPECIFIC_SERVICES_READY);
traceEnd();
// These are needed to propagate to the runnable below.
final NetworkManagementService networkManagementF = networkManagement;
final NetworkStatsService networkStatsF = networkStats;
final NetworkPolicyManagerService networkPolicyF = networkPolicy;
final ConnectivityService connectivityF = connectivity;
final LocationManagerService locationF = location;
final CountryDetectorService countryDetectorF = countryDetector;
final NetworkTimeUpdateService networkTimeUpdaterF = networkTimeUpdater;
final CommonTimeManagementService commonTimeMgmtServiceF = commonTimeMgmtService;
final InputManagerService inputManagerF = inputManager;
final TelephonyRegistry telephonyRegistryF = telephonyRegistry;
final MediaRouterService mediaRouterF = mediaRouter;
final MmsServiceBroker mmsServiceF = mmsService;
final IpSecService ipSecServiceF = ipSecService;
final WindowManagerService windowManagerF = wm;
// 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");
traceBeginAndSlog("StartActivityManagerReadyPhase");
addBootEvent("StartActivityManagerReadyPhase");
mSystemServiceManager.startBootPhase(
SystemService.PHASE_ACTIVITY_MANAGER_READY);
traceEnd();
addBootEvent("StartActivityManagerReadyPhase END");
traceBeginAndSlog("StartObservingNativeCrashes");
addBootEvent("StartObservingNativeCrashes");
try {
mActivityManagerService.startObservingNativeCrashes();
} catch (Throwable e) {
reportWtf("observing native crashes", e);
}
traceEnd();
addBootEvent("StartObservingNativeCrashes END");
// No dependency on Webview preparation in system server. But this should
// be completed before allowing 3rd party
final String WEBVIEW_PREPARATION = "WebViewFactoryPreparation";
Future> webviewPrep = null;
if (!mOnlyCore && mWebViewUpdateService != null) {
webviewPrep = SystemServerInitThreadPool.get().submit(() -> {
Slog.i(TAG, WEBVIEW_PREPARATION);
TimingsTraceLog traceLog = new TimingsTraceLog(
SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
traceLog.traceBegin(WEBVIEW_PREPARATION);
ConcurrentUtils.waitForFutureNoInterrupt(mZygotePreload, "Zygote preload");
mZygotePreload = null;
mWebViewUpdateService.prepareWebViewInSystemServer();
traceLog.traceEnd();
}, WEBVIEW_PREPARATION);
}
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
traceBeginAndSlog("StartCarServiceHelperService");
addBootEvent("StartCarServiceHelperService");
mSystemServiceManager.startService(CAR_SERVICE_HELPER_SERVICE_CLASS);
addBootEvent("StartCarServiceHelperService END");
traceEnd();
}
traceBeginAndSlog("StartSystemUI");
addBootEvent("StartSystemUI");
try {
startSystemUi(context, windowManagerF);
} catch (Throwable e) {
reportWtf("starting System UI", e);
}
addBootEvent("StartSystemUI END");
traceEnd();
traceBeginAndSlog("MakeNetworkManagementServiceReady");
addBootEvent("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();
}
addBootEvent("MakeNetworkManagementServiceReady END");
traceEnd();
traceBeginAndSlog("MakeIpSecServiceReady");
addBootEvent("MakeIpSecServiceReady");
try {
if (ipSecServiceF != null) ipSecServiceF.systemReady();
} catch (Throwable e) {
reportWtf("making IpSec Service ready", e);
}
addBootEvent("MakeIpSecServiceReady END");
traceEnd();
traceBeginAndSlog("MakeNetworkStatsServiceReady");
addBootEvent("MakeNetworkStatsServiceReady");
try {
if (networkStatsF != null) networkStatsF.systemReady();
} catch (Throwable e) {
reportWtf("making Network Stats Service ready", e);
}
addBootEvent("MakeNetworkStatsServiceReady END");
traceEnd();
traceBeginAndSlog("MakeConnectivityServiceReady");
addBootEvent("MakeConnectivityServiceReady");
try {
if (connectivityF != null) connectivityF.systemReady();
} catch (Throwable e) {
reportWtf("making Connectivity Service ready", e);
}
addBootEvent("MakeConnectivityServiceReady END");
traceEnd();
traceBeginAndSlog("MakeNetworkPolicyServiceReady");
addBootEvent("MakeNetworkPolicyServiceReady");
try {
if (networkPolicyF != null) {
networkPolicyF.systemReady(networkPolicyInitReadySignal);
}
} catch (Throwable e) {
reportWtf("making Network Policy Service ready", e);
}
addBootEvent("MakeNetworkPolicyServiceReady END");
traceEnd();
traceBeginAndSlog("StartWatchdog");
addBootEvent("StartWatchdog");
Watchdog.getInstance().start();
addBootEvent("StartWatchdog END");
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...
traceBeginAndSlog("PhaseThirdPartyAppsCanStart");
addBootEvent("PhaseThirdPartyAppsCanStart");
// confirm webview completion before starting 3rd party
if (webviewPrep != null) {
ConcurrentUtils.waitForFutureNoInterrupt(webviewPrep, WEBVIEW_PREPARATION);
}
mSystemServiceManager.startBootPhase(
SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
addBootEvent("PhaseThirdPartyAppsCanStart END");
traceEnd();
traceBeginAndSlog("MakeLocationServiceReady");
addBootEvent("MakeLocationServiceReady");
try {
if (locationF != null) locationF.systemRunning();
} catch (Throwable e) {
reportWtf("Notifying Location Service running", e);
}
addBootEvent("MakeLocationServiceReady END");
traceEnd();
traceBeginAndSlog("MakeCountryDetectionServiceReady");
addBootEvent("MakeCountryDetectionServiceReady");
try {
if (countryDetectorF != null) countryDetectorF.systemRunning();
} catch (Throwable e) {
reportWtf("Notifying CountryDetectorService running", e);
}
addBootEvent("MakeCountryDetectionServiceReady END");
traceEnd();
traceBeginAndSlog("MakeNetworkTimeUpdateReady");
addBootEvent("MakeNetworkTimeUpdateReady");
try {
if (networkTimeUpdaterF != null) networkTimeUpdaterF.systemRunning();
} catch (Throwable e) {
reportWtf("Notifying NetworkTimeService running", e);
}
addBootEvent("MakeNetworkTimeUpdateReady END");
traceEnd();
traceBeginAndSlog("MakeCommonTimeManagementServiceReady");
addBootEvent("MakeCommonTimeManagementServiceReady");
try {
if (commonTimeMgmtServiceF != null) {
commonTimeMgmtServiceF.systemRunning();
}
} catch (Throwable e) {
reportWtf("Notifying CommonTimeManagementService running", e);
}
addBootEvent("MakeCommonTimeManagementServiceReady END");
traceEnd();
traceBeginAndSlog("MakeInputManagerServiceReady");
addBootEvent("MakeInputManagerServiceReady");
try {
// TODO(BT) Pass parameter to input manager
if (inputManagerF != null) inputManagerF.systemRunning();
} catch (Throwable e) {
reportWtf("Notifying InputManagerService running", e);
}
addBootEvent("MakeInputManagerServiceReady END");
traceEnd();
traceBeginAndSlog("MakeTelephonyRegistryReady");
addBootEvent("MakeTelephonyRegistryReady");
try {
if (telephonyRegistryF != null) telephonyRegistryF.systemRunning();
} catch (Throwable e) {
reportWtf("Notifying TelephonyRegistry running", e);
}
addBootEvent("MakeTelephonyRegistryReady END");
traceEnd();
traceBeginAndSlog("MakeMediaRouterServiceReady");
addBootEvent("MakeMediaRouterServiceReady");
try {
if (mediaRouterF != null) mediaRouterF.systemRunning();
} catch (Throwable e) {
reportWtf("Notifying MediaRouterService running", e);
}
addBootEvent("MakeMediaRouterServiceReady END");
traceEnd();
traceBeginAndSlog("MakeMmsServiceReady");
addBootEvent("MakeMmsServiceReady");
try {
if (mmsServiceF != null) mmsServiceF.systemRunning();
} catch (Throwable e) {
reportWtf("Notifying MmsService running", e);
}
addBootEvent("MakeMmsServiceReady END");
traceEnd();
traceBeginAndSlog("IncidentDaemonReady");
addBootEvent("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);
}
addBootEvent("IncidentDaemonReady END");
traceEnd();
}, BOOT_TIMINGS_TRACE_LOG);
traceBeginAndSlog("ScheduleIdleOptimize");
addBootEvent("ScheduleIdleOptimize");
try {
BackgroundDexOptService.scheduleIdleOptimize(context);
} catch (Throwable e) {
reportWtf("ScheduleIdleOptimize", e);
}
addBootEvent("ScheduleIdleOptimize END");
traceEnd();
}
如图所示,图中为SystemServer 启动的服务:
System server的启动过程做了如上事情,System Server启动完成后,会启动HOME APP,详情请见下节。