Zygote家的大儿子-SystemServer
本文基于 Android 9.0 , 代码仓库地址 : android_9.0.0_r45文中源码链接: SystemServer.java SystemServiceManager.java SystemService.java 首先来回顾一下上篇文章 Java 世界的盘古和女娲 —— Zygote ,主要介绍了 Android 世界中的第一个 Java 进程 Zygote,它的主要工作流程如下: registerServerSocketFromEnv(), 注册服务端 socket,用于和客户端进程通信preload(),预加载一系列资源,提高应用启动速度forkSystemServer(),创建 system_server 进程功成身退,调用 runSelectLoop() 等待响应客户端请求,创建应用进程本篇文章的主角 system_server 进程是 Zygote 进程 fork 出的第一个进程,它负责管理和启动整个 Framework 层。 再来看看 Gityuan 的这张图片,找一下 System Server 的位置,它承载了各类系统服务的创建和启动。关于 system_server 进程的创建流程,上篇文章中已经做了详细介绍,这里再简单看一下流程图: 最终会调用到 SystemServer.main() 方法。下面就以此为起点,来具体分析 SystemServer 都做了些什么。 SystemServer 启动流程public static void main(String[] args) { new SystemServer().run();}接着看 run() 方法。 private void run() { try { ...... // 如果设备时间早于 1970 年,很多 API 处理负数时会 crash。所以直接设置为 1970 年 1 月 1 日 if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) { Slog.w(TAG, "System clock is before 1970; setting to 1970."); SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME); } // 未设置时区的话默认设为 GMT String timezoneProperty = SystemProperties.get("persist.sys.timezone"); if (timezoneProperty == null || timezoneProperty.isEmpty()) { Slog.w(TAG, "Timezone not set; setting to 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.setWarnOnBlocking(true); // The system server should always load safe labels PackageItemInfo.setForceSafeLabels(true); // 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!"); int uptimeMillis = (int) SystemClock.elapsedRealtime(); EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, uptimeMillis); if (!mRuntimeRestart) { MetricsLogger.histogram(null, "boot_system_server_init", uptimeMillis); } // 设置虚拟机运行库路径 SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary()); // Mmmmmm... more memory! // 清除虚拟机内存增长限制,允许应用申请更多内存 VMRuntime.getRuntime().clearGrowthLimit(); // 设置堆内存的有效利用率为 0.8,(可能被忽略) VMRuntime.getRuntime().setTargetHeapUtilization(0.8f); // 确保指纹信息已经定义 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); // 确保系统的 Binder 调用总是运行在前台优先级 BinderInternal.disableBackgroundScheduling(true); // Increase the number of binder threads in system_server BinderInternal.setMaxThreads(sMaxBinderThreads); // Prepare the main looper thread (this thread). android.os.Process.setThreadPriority( android.os.Process.THREAD_PRIORITY_FOREGROUND); android.os.Process.setCanSelfBackground(false); // 1. 创建主线程 Looper Looper.prepareMainLooper(); Looper.getMainLooper().setSlowLogThresholdMs( SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS); // 初始化 native 服务,加载 libandroid_servers.so System.loadLibrary("android_servers"); // 检查上次关机是否失败,可能不会有返回值 performPendingShutdown(); // 2. 初始化系统上下文 createSystemContext(); // 3. 创建系统服务管理 SystemServiceManager // 并将 mSystemServiceManager 注册到 sLocalServiceObjects 中 mSystemServiceManager = new SystemServiceManager(mSystemContext); mSystemServiceManager.setStartInfo(mRuntimeRestart, mRuntimeStartElapsedTime, mRuntimeStartUptime); LocalServices.addService(SystemServiceManager.class, mSystemServiceManager); // Prepare the thread pool for init tasks that can be parallelized SystemServerInitThreadPool.get(); } finally { traceEnd(); // InitBeforeStartServices } // Start services. try { traceBeginAndSlog("StartServices"); startBootstrapServices(); // 4. 启动系统引导服务 startCoreServices(); // 5. 启动系统核心服务 startOtherServices(); // 6. 启动其他服务 SystemServerInitThreadPool.shutdown(); } catch (Throwable ex) { Slog.e("System", "******************************************"); Slog.e("System", "************ Failure starting system services", ex); throw ex; } finally { traceEnd(); } StrictMode.initVmDefaults(null); if (!mRuntimeRestart && !isFirstBootOrUpgrade()) { int uptimeMillis = (int) SystemClock.elapsedRealtime(); MetricsLogger.histogram(null, "boot_system_server_ready", uptimeMillis); final int MAX_UPTIME_MILLIS = 60 * 1000; if (uptimeMillis > MAX_UPTIME_MILLIS) { Slog.wtf(SYSTEM_SERVER_TIMING_TAG, "SystemServer init took too long. uptimeMillis=" + uptimeMillis); } } // 7. Loop forever. Looper.loop(); throw new RuntimeException("Main thread loop unexpectedly exited");}代码虽然比较长,但是逻辑很清晰。我在注释里标记了比较重要的 7 个步骤,逐一分析。 ...