由于源码分析的代码量比较大,大部分博客网站的内容显示页面都比较窄,显示出来的效果都异常丑陋,所以您也可以直接查看 《 Thinking in Android 》 来阅读这边文章,希望这篇文章能帮你梳理清楚 “SystemServer 进程的原理”。
关键类 | 路径 |
---|---|
com_android_internal_os_Zygote.cpp | frameworks/base/core/jni/com_android_internal_os_Zygote.cpp |
AndroidRuntime.cpp | frameworks/base/core/jni/AndroidRuntime.cpp |
ZygoteInit.java | frameworks/base/core/java/com/android/internal/os/ZygoteInit.java |
Zygote.java | frameworks/base/core/java/com/android/internal/os/Zygote.java |
ActivityThread.java | frameworks/base/core/java/android/app/ActivityThread.java |
ContextImpl.java.java | frameworks/base/core/java/android/app/ContextImpl.java |
LoadedApk.java.java | frameworks/base/core/java/android/app/LoadedApk.java |
SystemServer.java | frameworks/base/services/java/com/android/server/SystemServer.java |
RuntimeInit.java | frameworks/base/core/java/com/android/internal/os/RuntimeInit.java |
app_main.cpp | frameworks/base/cmds/app_process/app_main.cpp |
SystemServiceManager.java | frameworks/base/services/core/java/com/android/server/SystemServiceManager.java |
SystemServer
服务进程是 Android 系统 Java 层框架的核心,它维护着 Android 系统的 核心服务
,比如:ActivityManagerService
、WindowManagerService
、PackageManagerService
等,是 Android 系统中一个非常重要的进程。
在 Android 系统中,应用程序出现问题,对系统影响不大,而 Init
、Zygote
、SystemServer
三大进程对系统的影响则非常大,因为其中任何一个 crash,都会造成系统崩溃,出现重启现象。
SystemServer
是由 Zygote
孵化而来的一个进程,通过 ps 命令,我们发现其进程名为:system_server
。
在分析 zygote 进程 时,我们知道当 zygote 进程进入到 java 世界后,在 ZygoteInit.java
中,将调用 forkSystemServer
方法启动 SystemServer 进程。
// frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
public class ZygoteInit {
public static void main(String argv[]) {
try {
if (startSystemServer) {
// fork 出 system_server
Runnable r = forkSystemServer(abiList, zygoteSocketName, zygoteServer);
if (r != null) {
r.run();
return;
}
}
}
}
private static Runnable forkSystemServer(String abiList, String socketName,
ZygoteServer zygoteServer) {
try {
... ...
/* Request to fork the system server process */
pid = Zygote.forkSystemServer(
parsedArgs.mUid, parsedArgs.mGid,
parsedArgs.mGids,
parsedArgs.mRuntimeFlags,
null,
parsedArgs.mPermittedCapabilities,
parsedArgs.mEffectiveCapabilities);
} catch (IllegalArgumentException ex) {
throw new RuntimeException(ex);
}
}
}
// frameworks/base/core/java/com/android/internal/os/Zygote.java
public final class Zygote {
public static int forkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
ZygoteHooks.preFork();
// Resets nice priority for zygote process.
resetNicePriority();
// 调用 nativeForkSystemServer() 方法进一步处理,它是一个 native 方法
int pid = nativeForkSystemServer(
uid, gid, gids, runtimeFlags, rlimits,
permittedCapabilities, effectiveCapabilities);
// Enable tracing as soon as we enter the system_server.
if (pid == 0) {
Trace.setTracingEnabled(true, runtimeFlags);
}
ZygoteHooks.postForkCommon();
return pid;
}
}
我们来看看对应的 native 方法:
// frameworks/base/core/jni/com_android_internal_os_Zygote.cpp
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 permitted_capabilities,
jlong effective_capabilities) {
... ...
// 传入一堆参数,进行实际的 "分裂" 工作,fork 出一个新的进程
pid_t pid = ForkCommon(env, true,
fds_to_close,
fds_to_ignore);
if (pid == 0) {
SpecializeCommon(env, uid, gid, gids, runtime_flags, rlimits,
permitted_capabilities, effective_capabilities,
MOUNT_EXTERNAL_DEFAULT, nullptr, nullptr, true,
false, nullptr, nullptr);
} else if (pid > 0) {
// The zygote process checks whether the child process has died or not.
ALOGI("System server process %d has been created", pid);
// 这里 SystemServer 进程已经创建出来,pid > 0 说明在父进程中
// 将子进程 SystemServer 的 pid 存在 zygote 进程的全局变量中
gSystemServerPid = pid;
int status;
if (waitpid(pid, &status, WNOHANG) == pid) {
// 小概率,SystemServer 进程刚创建,就 crash;此时需要重启 zygote
ALOGE("System server process %d has died. Restarting Zygote!", pid);
RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");
}
... ...
}
return pid;
}
上述代码中,实际的“分裂”工作由函数 ForkCommon()
和 SpecializeCommon()
完成。
// frameworks/base/core/jni/com_android_internal_os_Zygote.cpp
// Utility routine to fork a process from the zygote.
static pid_t ForkCommon(JNIEnv* env, bool is_system_server,
const std::vector<int>& fds_to_close,
const std::vector<int>& fds_to_ignore) {
SetSignalHandlers();
... ...
pid_t pid = fork(); // 注册子进程信号监听器
... ...
return pid;
}
从上面的代码可以看出,ForkCommon()
最终是通过 fork
的方式,分裂出子进程。
这里需要注意的是,在 zygote 进程 fork 之前,调用了 SetSignalHandlers()
函数注册了一个 子进程信号监听器
。
// frameworks/base/core/jni/com_android_internal_os_Zygote.cpp
static void SetSignalHandlers() {
struct sigaction sig_chld = {};
sig_chld.sa_handler = SigChldHandler;
// 该信号监听器关注子进程结束,对应的处理函数为 SigChldHandler
if (sigaction(SIGCHLD, &sig_chld, nullptr) < 0) {
ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));
}
struct sigaction sig_hup = {};
sig_hup.sa_handler = SIG_IGN;
if (sigaction(SIGHUP, &sig_hup, nullptr) < 0) {
ALOGW("Error setting SIGHUP handler: %s", strerror(errno));
}
}
从上面的代码可以看出,SetSignalHandlers()
函数将注册一个信号处理器:SigChldHandler
,来监听子进程的死亡。当子进程死亡后,就会产生一个信号,Zygote 进程收到该信号之后就会调用 SigChldHandler()
进行处理。需要注意的是,zygote 的信号监听器,关注的是 zygote 所有的子进程,而不只是 SystemServer 进程(每次创建一个新的进程时,zygote 都会注册对应的监听器)。
// frameworks/base/core/jni/com_android_internal_os_Zygote.cpp
static void SigChldHandler(int /*signal_number*/) {
pid_t pid;
int status;
int64_t usaps_removed = 0;
while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
// 通过 status 判断子进程结束的原因,并打印相应的 log
... ...
if (pid == gSystemServerPid) { // 上文已经介绍过,gSystemServerPid 中记录了 SystemServer 的 pid
kill(getpid(), SIGKILL); // 如果结束的子进程为 SystemServer,Zygote 也将结束自己
}
}
... ...
}
发现没?所有 zygote 的子进程中,zygote 只关心了 SystemServer 的死活,它们是 “生死共存亡的”,当其它子进程 crash 时,zygote 只打印了 log 信息。
我们之前在分析 init 的 main() 方法的最后,关注到如下代码:
int main(int argc, char** argv) {
... ...
while (true) {
// By default, sleep until something happens.
int epoll_timeout_ms = -1;
if (do_shutdown && !shutting_down) {
do_shutdown = false;
if (HandlePowerctlMessage(shutdown_command)) {
shutting_down = true;
}
}
if (!(waiting_for_prop || Service::is_exec_service_running())) {
am.ExecuteOneCommand();
}
if (!(waiting_for_prop || Service::is_exec_service_running())) {
if (!shutting_down) {
// 重启死掉的 service,如果是 Zygote 死掉了,就重启 Zygote
auto next_process_restart_time = RestartProcesses();
... ...
}
}
在 init 的 main() 函数中,如果 Zygote 停止工作,Init 进程就调用 RestartProcesses()
函数来重启 Zygote。
所以,init 进程
、Zygote 进程
、SystemServer 进程
紧密相连,任何一个都不能出问题!
通过 fork 创建出 SystemServer 进程后,SystemServer 进程会调用 handleSystemServerProcess
函数,开始执行自己的工作。
// frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
public class ZygoteInit {
private static Runnable forkSystemServer(String abiList, String socketName,
ZygoteServer zygoteServer) {
... ...
/* For child process */
if (pid == 0) {
if (hasSecondZygote(abiList)) {
waitForSecondaryZygote(socketName);
}
zygoteServer.closeServerSocket();
return handleSystemServerProcess(parsedArgs); // SystemServer 进程处理自己的工作
}
return null;
}
}
// frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
public class ZygoteInit {
/**
* Finish remaining work for the newly forked system server process.
*/
private static Runnable handleSystemServerProcess(ZygoteArguments parsedArgs) {
if (parsedArgs.mNiceName != null) {
Process.setArgV0(parsedArgs.mNiceName);
}
// 加载 SystemServer 对应的文件
final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH");
if (systemServerClasspath != null) {
if (performSystemServerDexOpt(systemServerClasspath)) {
sCachedSystemServerClassLoader = null;
}
boolean profileSystemServer = SystemProperties.getBoolean(
"dalvik.vm.profilesystemserver", false);
if (profileSystemServer && (Build.IS_USERDEBUG || Build.IS_ENG)) {
try {
prepareSystemServerProfile(systemServerClasspath);
} catch (Exception e) {
Log.wtf(TAG, "Failed to set up system server profile", e);
}
}
}
if (parsedArgs.mInvokeWith != null) {
... ...
} else {
createSystemServerClassLoader(); // 构建对应的 ClassLoader
ClassLoader cl = sCachedSystemServerClassLoader;
if (cl != null) {
Thread.currentThread().setContextClassLoader(cl);
}
// 将剩余参数及 classLoader 递交给 ZygoteInit 的 zygoteInit() 函数
return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,
parsedArgs.mRemainingArgs, cl);
}
}
/* should never reach here */
}
从上面的代码可以看出,接下来的流程进入到 ZygoteInit 的 zygoteInit()
函数。zygoteInit 函数将根据 classLoader 和参数,完成不同进程所需要的初始化工作(SystemServer 进程与 Zygote 的其它子进程均将使用 zygoteInit 函数)。
// frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
public class ZygoteInit {
public static final Runnable zygoteInit(int targetSdkVersion, String[] argv,
ClassLoader classLoader) {
if (RuntimeInit.DEBUG) {
Slog.d(RuntimeInit.TAG, "RuntimeInit: Starting application from zygote");
}
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ZygoteInit");
RuntimeInit.redirectLogStreams();
RuntimeInit.commonInit(); // 常规初始化操作,暂时不做深入
ZygoteInit.nativeZygoteInit(); // native 方法,为 Binder 通信做好准备
return RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader); // 见 1.12
}
}
// frameworks/base/core/jni/AndroidRuntime.cpp
static void com_android_internal_os_ZygoteInit_nativeZygoteInit(JNIEnv* env, jobject clazz)
{
gCurRuntime->onZygoteInit(); // gCurRuntime 指的是什么?
}
我们知道,在 app_main.cpp
的 main
函数中,创建了 AppRuntime
:
int main(int argc, char* const argv[])
{
AppRuntime runtime(argv[0], computeArgBlockSize(argc, argv));
}
AppRuntime 定义如下:
class AppRuntime : public AndroidRuntime
{
public:
AppRuntime(char* argBlockStart, const size_t argBlockLength)
: AndroidRuntime(argBlockStart, argBlockLength)
, mClass(NULL)
{
}
... ...
}
看看 AppRuntime 的父类 AndroidRuntime:
AndroidRuntime::AndroidRuntime(char* argBlockStart, const size_t argBlockLength) :
mExitWithoutCleanup(false),
mArgBlockStart(argBlockStart),
mArgBlockLength(argBlockLength)
{
SkGraphics::Init();
// Pre-allocate enough space to hold a fair number of options.
mOptions.setCapacity(20);
assert(gCurRuntime == NULL); // one per process
gCurRuntime = this;
}
从代码可以看出,AndroidRuntime 初始化时定义了 gCurRuntime
。gCurRuntime 指向对象自身,也就是说 gCurRuntime 指向的是 AppRuntime 对象
。
由于 SystemServer 进程由 zygote 进程 fork 出来,所以 SystemServer 进程中也存在 gCurRuntime 对象,类型为 AppRuntime
。
至此我们知道,Native 函数中 gCurRuntime->onZygoteInit
将调用 AppRuntime
中的 onZygoteInit()
。
// frameworks/base/cmds/app_process/app_main.cpp
virtual void onZygoteInit()
{
sp<ProcessState> proc = ProcessState::self();
ALOGV("App process: starting thread pool.\n");
proc->startThreadPool(); // 启动一个线程,用于 binder 通信
}
// frameworks/base/core/java/com/android/internal/os/RuntimeInit.java
public class RuntimeInit {
protected static Runnable applicationInit(int targetSdkVersion, String[] argv,
ClassLoader classLoader) {
// 设置一些进程退出的处理策略,可用堆栈上限等
... ...
// Remaining arguments are passed to the start class's static main
return findStaticMain(args.startClass, args.startArgs, classLoader);
}
}
跟踪 findStaticMain()
:
// frameworks/base/core/java/com/android/internal/os/RuntimeInit.java
public class RuntimeInit {
protected static Runnable findStaticMain(String className, String[] argv,
ClassLoader classLoader) {
// className 为进行初始化工作的进程类名
// 在 SystemServer 初始化时,为 com.android.server.SystemServer
Class<?> cl;
try {
// 下面就是通过反射得到对应类的 main 方法
cl = Class.forName(className, true, classLoader);
} catch (ClassNotFoundException ex) {
throw new RuntimeException(
"Missing class when invoking static main " + className,
ex);
}
... ...
return new MethodAndArgsCaller(m, argv); // 捕获 MethodAndArgsCaller 异常
}
}
接下来就进入了 SystemServer.java
的 main()
函数处理流程:
// frameworks/base/services/java/com/android/server/SystemServer.java
public final class SystemServer {
/**
* The main entry point from zygote.
*/
public static void main(String[] args) {
new SystemServer().run(); // 创建并运行,简单粗暴!
}
}
这里比较简单,只是 new 出一个 SystemServer 对象
并执行其 run()
方法。
// frameworks/base/services/java/com/android/server/SystemServer.java
public final class SystemServer {
private void run() {
try {
traceBeginAndSlog("InitBeforeStartServices");
... ...
// 如何系统时钟早于1970年,则设置系统始终从1970年开始
if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
Slog.w(TAG, "System clock is before 1970; setting to 1970.");
SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
}
... ...
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", "");
}
... ...
// 清除 vm 内存增长上限,由于启动过程需要较多的虚拟机内存空间
VMRuntime.getRuntime().clearGrowthLimit();
// 设置堆栈利用率,GC 后会重新计算堆栈空间大小
VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
// 针对部分设备依赖于运行时就产生指纹信息,因此需要在开机完成前已经定义
Build.ensureFingerprintProperty();
// 访问环境变量前,需要明确地指定用户
Environment.setUserRequired(true);
... ...
// 加载动态库 libandroid_services.so
System.loadLibrary("android_servers");
// 检测上次关机过程是否失败,该方法可能不会返回
performPendingShutdown();
// 在 SystemServer 进程中也需要创建 Context 对象,初始化系统上下文
createSystemContext();
// 创建 SystemServiceManager 对象
mSystemServiceManager = new SystemServiceManager(mSystemContext);
// SystemServer 进程主要是用来构建系统各种 service 服务,
// 而 SystemServiceManager 就是这些服务的管理对象
mSystemServiceManager.setStartInfo(mRuntimeRestart,
mRuntimeStartElapsedTime, mRuntimeStartUptime);
// 将 SystemServiceManager 对象保存到 SystemServer 进程中的一个数据结构中
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(); // 主要用于启动系统 Boot 级服务
startCoreServices(); // 主要用于启动系统核心的服务
startOtherServices(); // 主要用于启动一些非紧要或者非需要及时启动的服务
SystemServerInitThreadPool.shutdown();
} catch (Throwable ex) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting system services", ex);
throw ex;
} finally {
traceEnd();
}
... ...
// 启动looper,以处理到来的消息,一直循环执行
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
}
以上就是 SystemServer.run()
方法的整个流程,简化如下:
// frameworks/base/services/java/com/android/server/SystemServer.java
public final class SystemServer {
private void run() {
try {
// Initialize the system context.
createSystemContext(); // 01. 初始化系统上下文
// 02. 创建系统服务管理
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
} finally {
traceEnd(); // InitBeforeStartServices
}
// 03.启动系统各种服务
try {
startBootstrapServices(); // 启动引导服务
startCoreServices(); // 启动核心服务
startOtherServices(); // 启动其他服务
SystemServerInitThreadPool.shutdown();
}
// Loop forever.
Looper.loop(); // 一直循环执行
throw new RuntimeException("Main thread loop unexpectedly exited");
}
}
接下来我们针对 SystemServer 所做的 三部分工作
单独分析!
// frameworks/base/services/java/com/android/server/SystemServer.java
public final class SystemServer {
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);
}
}
跟踪 systemMain()
方法:
// frameworks/base/core/java/android/app/ActivityThread.java
public final class ActivityThread extends ClientTransactionHandler {
public static ActivityThread systemMain() {
// The system process on low-memory devices do not get to use hardware
// accelerated drawing, since this can add too much overhead to the
// process.
if (!ActivityManager.isHighEndGfx()) {
ThreadedRenderer.disable(true); // 对于低内存的设备,禁用硬件加速
} else {
ThreadedRenderer.enableForegroundTrimming();
}
ActivityThread thread = new ActivityThread();
thread.attach(true, 0); // 调用 attach() 方法
return thread;
}
}
跟踪 attach()
方法:
// frameworks/base/core/java/android/app/ActivityThread.java
public final class ActivityThread extends ClientTransactionHandler {
private void attach(boolean system, long startSeq) {
sCurrentActivityThread = this;
mSystemThread = system;
if (!system) {
... ...
} else {
// Don't set application object here -- if the system crashes,
// we can't display an alert, we just want to die die die.
// 设置 SystemServer 进程在 DDMS 中显示的名字为 "system_process"
android.ddm.DdmHandleAppName.setAppName("system_process",
UserHandle.myUserId()); // 如不设置,则显示"?",无法调试该进程
try {
mInstrumentation = new Instrumentation();
mInstrumentation.basicInit(this);
// 首先通过 getSystemContext() 创建系统上下文,然后创建应用上下文
ContextImpl context = ContextImpl.createAppContext(
this, getSystemContext().mPackageInfo);
// 创建 Application
mInitialApplication = context.mPackageInfo.makeApplication(true, null);
// 调用 Application的 onCreate()
mInitialApplication.onCreate();
} catch (Exception e) {
throw new RuntimeException(
"Unable to instantiate Application():" + e.toString(), e);
}
}
... ...
ViewRootImpl.ConfigChangedCallback configChangedCallback
= (Configuration globalConfig) -> {
synchronized (mResourcesManager) {
// We need to apply this change to the resources immediately, because upon returning
// the view hierarchy will be informed about it.
if (mResourcesManager.applyConfigurationToResourcesLocked(globalConfig,
null /* compat */)) {
updateLocaleListFromAppContext(mInitialApplication.getApplicationContext(),
mResourcesManager.getConfiguration().getLocales());
// This actually changed the resources! Tell everyone about it.
if (mPendingConfiguration == null
|| mPendingConfiguration.isOtherSeqNewer(globalConfig)) {
mPendingConfiguration = globalConfig;
sendMessage(H.CONFIGURATION_CHANGED, globalConfig);
}
}
}
};
// 添加回调
ViewRootImpl.addConfigCallback(configChangedCallback);
}
}
我们发现 attach()
方法主要做了四件事:
(1)创建系统上下文:getSystemContext()
;
(2)创建应用上下文:createAppContext()
;
(3)创建 Application:makeApplication()
;
(4)添加回调 configChangedCallback
到 ViewRootImpl
。
(1)创建系统上下文
// frameworks/base/core/java/android/app/ActivityThread.java
public final class ActivityThread extends ClientTransactionHandler {
public ContextImpl getSystemContext() {
synchronized (this) {
if (mSystemContext == null) {
mSystemContext = ContextImpl.createSystemContext(this);
}
return mSystemContext;
}
}
}
// frameworks/base/core/java/android/app/ContextImpl.java
class ContextImpl extends Context {
static ContextImpl createSystemContext(ActivityThread mainThread) {
// 这边 new 出来的 LoadedApk 将作为创建应用上下文的参数 packageInfo
LoadedApk packageInfo = new LoadedApk(mainThread);
// ContextImpl() 创建系统上下文
ContextImpl context = new ContextImpl(null, mainThread, packageInfo, null, null, null, 0,
null, null);
context.setResources(packageInfo.getResources());
context.mResources.updateConfiguration(context.mResourcesManager.getConfiguration(),
context.mResourcesManager.getDisplayMetrics());
return context;
}
}
(2)创建应用上下文
// frameworks/base/core/java/android/app/ContextImpl.java
class ContextImpl extends Context {
static ContextImpl createAppContext(ActivityThread mainThread, LoadedApk packageInfo) {
return createAppContext(mainThread, packageInfo, null);
}
static ContextImpl createAppContext(ActivityThread mainThread, LoadedApk packageInfo,
String opPackageName) {
if (packageInfo == null) throw new IllegalArgumentException("packageInfo");
// ContextImpl()创建应用上下文
ContextImpl context = new ContextImpl(null, mainThread, packageInfo, null, null, null, 0,
null, opPackageName);
context.setResources(packageInfo.getResources());
return context;
}
}
我们可以看出:new ContextImpl()
时,系统上下文和应用上下文的参数是一样的,createAppContext()
中的参数 packageInfo
,就是 createSystemContext()
中 new 的 LoadedApk
。
创建完成之后,系统上下文赋值给了 ActivityThread
的成员变量 mSystemContext
,而应用上下文只是作为函数中的局部变量临时使用。
(3)创建 Application
// frameworks/base/core/java/android/app/LoadedApk.java
public final class LoadedApk {
public Application makeApplication(boolean forceDefaultAppClass,
Instrumentation instrumentation) {
if (mApplication != null) {
return mApplication;
}
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "makeApplication");
Application app = null;
String appClass = mApplicationInfo.className;
if (forceDefaultAppClass || (appClass == null)) { // forceDefaultAppClass 为 true
appClass = "android.app.Application";
}
try {
java.lang.ClassLoader cl = getClassLoader();
// 此 LoadedApk 对象是 createSystemContext 时 new 的,mPackageName = "android"
if (!mPackageName.equals("android")) {
initializeJavaContextClassLoader();
}
// 又创建了一个局部应用上下文
ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
// 创建 Application
app = mActivityThread.mInstrumentation.newApplication(
cl, appClass, appContext);
appContext.setOuterContext(app);
} catch (Exception e) {
if (!mActivityThread.mInstrumentation.onException(app, e)) {
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
throw new RuntimeException(
"Unable to instantiate application " + appClass
+ ": " + e.toString(), e);
}
}
// 将前面创建的 app 添加到应用列表
mActivityThread.mAllApplications.add(app);
mApplication = app;
... ...
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
return app;
}
}
我们回顾下 创建系统服务管理
相关代码:
// frameworks/base/services/java/com/android/server/SystemServer.java
public final class SystemServer {
private void run() {
try {
// Initialize the system context.
createSystemContext(); // 01. 初始化系统上下文
// 02. 创建系统服务管理
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
} finally {
traceEnd(); // InitBeforeStartServices
}
... ...
}
这一步比较简单,只是 new 了一个 SystemServiceManager
,并将其添加到本地服务列表中。mSystemContext
为第一步中创建的系统上下文。本地服务列表是以类为 key 保存的一个列表,即列表中某种类型的对象最多只能有一个。
new SystemServiceManager()
// frameworks/base/services/core/java/com/android/server/SystemServiceManager.java
public class SystemServiceManager {
... ...
// 系统服务列表,系统服务必须继承 SystemService
private final ArrayList<SystemService> mServices = new ArrayList<SystemService>();
// 当前处于开机过程的哪个阶段
private int mCurrentPhase = -1;
SystemServiceManager(Context context) {
mContext = context;
}
@SuppressWarnings("unchecked")
// 通过类名启动系统服务,可能会找不到类而抛异常
public SystemService startService(String className) {
final Class<SystemService> serviceClass;
try {
serviceClass = (Class<SystemService>)Class.forName(className);
} catch (ClassNotFoundException ex) {
Slog.i(TAG, "Starting " + className);
throw new RuntimeException("Failed to create service " + className
+ ": 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", ex);
}
return startService(serviceClass);
}
@SuppressWarnings("unchecked")
// 创建并启动系统服务,系统服务类必须继承 SystemService
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 {
Constructor<T> constructor = serviceClass.getConstructor(Context.class);
service = constructor.newInstance(mContext);
} catch (InstantiationException ex) {
... ...
}
startService(service);
return service;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
}
public void startService(@NonNull final SystemService service) {
// Register it.
mServices.add(service);
// Start it.
long time = SystemClock.elapsedRealtime();
try {
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");
}
// 通知系统服务到了开机的哪个阶段,会遍历调用所有系统服务的 onBootPhase() 函数
public void startBootPhase(final int phase) {
... ...
try {
Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "OnBootPhase " + phase);
final int serviceLen = mServices.size();
for (int i = 0; i < serviceLen; i++) {
final SystemService service = mServices.get(i);
long time = SystemClock.elapsedRealtime();
Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, service.getClass().getName());
try {
service.onBootPhase(mCurrentPhase);
} catch (Exception ex) {
throw new RuntimeException("Failed to boot service "
+ service.getClass().getName()
+ ": onBootPhase threw an exception during phase "
+ mCurrentPhase, ex);
}
warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onBootPhase");
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
} finally {
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
}
}
// frameworks/base/services/java/com/android/server/SystemServer.java
public final class SystemServer {
private void run() {
// 01. 初始化系统上下文
// 02. 创建系统服务管理
// 03.启动系统各种服务
try {
startBootstrapServices(); // 启动引导服务
startCoreServices(); // 启动核心服务
startOtherServices(); // 启动其他服务
SystemServerInitThreadPool.shutdown();
}
// Loop forever.
Looper.loop(); // 一直循环执行
throw new RuntimeException("Main thread loop unexpectedly exited");
}
}
(1)启动引导服务
// frameworks/base/services/java/com/android/server/SystemServer.java
public final class SystemServer {
/**
* 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() {
... ...
// 启动 Installer 服务,阻塞等待与 installd 建立 socket 通道
Installer installer = mSystemServiceManager.startService(Installer.class);
mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);
mSystemServiceManager.startService(UriGrantsManagerService.Lifecycle.class);
// 启动 ActivityManagerService
ActivityTaskManagerService atm = mSystemServiceManager.startService(
ActivityTaskManagerService.Lifecycle.class).getService();
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
mWindowManagerGlobalLock = atm.getGlobalLock();
// 启动 PowerManagerService
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
mSystemServiceManager.startService(ThermalManagerService.class);
// PowerManagerService 就绪,AMS 初始化电源管理
mActivityManagerService.initPowerManagement();
mActivityManagerService.initPowerManagement();
mSystemServiceManager.startService(RecoverySystemService.class);
RescueParty.noteBoot(mSystemContext);
// 启动 LightsService
mSystemServiceManager.startService(LightsService.class);
// 启动 DisplayManagerService
mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
// We need the default display before we can initialize the package manager.
mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
// 当设备正在加密时,仅运行核心应用
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;
}
// Start the package manager.
if (!mRuntimeRestart) {
MetricsLogger.histogram(null, "boot_package_manager_init_start",
(int) SystemClock.elapsedRealtime());
}
// 启动 PackageManagerService
try {
Watchdog.getInstance().pauseWatchingCurrentThread("packagemanagermain");
mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
} finally {
Watchdog.getInstance().resumeWatchingCurrentThread("packagemanagermain");
}
mFirstBoot = mPackageManagerService.isFirstBoot();
mPackageManager = mSystemContext.getPackageManager();
... ...
// 将 UserManagerService 添加到服务列表,该服务是在 PackageManagerService 中初始化的
mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
// 初始化用来缓存包资源的属性缓存
AttributeCache.init(mSystemContext);
// Set up the Application instance for the system process and get started.
mActivityManagerService.setSystemProcess();
... ...
mSensorServiceStart = SystemServerInitThreadPool.get().submit(() -> {
TimingsTraceLog traceLog = new TimingsTraceLog(
SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
traceLog.traceBegin(START_SENSOR_SERVICE);
startSensorService(); // 启动传感器服务
traceLog.traceEnd();
}, START_SENSOR_SERVICE);
}
}
首先等待 installd
启动完成,然后启动一些相互依赖的关键服务。
(2)启动核心服务
接下来继续看下核心服务的启动:
// frameworks/base/services/java/com/android/server/SystemServer.java
public final class SystemServer {
/**
* Starts some essential services that are not tangled up in the bootstrap process.
*/
private void startCoreServices() {
// 启动 BatteryService,用于统计电池电量,需要 LightService
mSystemServiceManager.startService(BatteryService.class);
// 启动 UsageStatsService,用于统计应用使用情况
mSystemServiceManager.startService(UsageStatsService.class);
mActivityManagerService.setUsageStatsManager(
LocalServices.getService(UsageStatsManagerInternal.class));
// 启动 WebViewUpdateService
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) {
mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
}
.... ...
}
}
(3)启动其他服务
代码很长(1200多行…),但是逻辑简单,主要是启动各种服务。
// frameworks/base/services/java/com/android/server/SystemServer.java
public final class SystemServer {
/**
* Starts a miscellaneous grab bag of stuff that has yet to be refactored and organized.
*/
private void startOtherServices() {
... ...
try {
... ...
// 调度策略
ServiceManager.addService("scheduling_policy", new SchedulingPolicyService());
mSystemServiceManager.startService(TelecomLoaderService.class);
// 提供电话注册、管理服务,可以获取电话的链接状态、信号强度等
telephonyRegistry = new TelephonyRegistry(context);
ServiceManager.addService("telephony.registry", telephonyRegistry);
mEntropyMixer = new EntropyMixer(context);
mContentResolver = context.getContentResolver();
// 提供所有账号、密码、认证管理等等的服务
mSystemServiceManager.startService(ACCOUNT_SERVICE_CLASS);
... ...
// 振动器服务
vibrator = new VibratorService(context);
ServiceManager.addService("vibrator", vibrator);
... ...
inputManager = new InputManagerService(context);
// WMS needs sensor service ready
ConcurrentUtils.waitForFutureNoInterrupt(mSensorServiceStart, START_SENSOR_SERVICE);
mSensorServiceStart = null;
wm = WindowManagerService.main(context, inputManager, !mFirstBoot, mOnlyCore,
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);
... ...
} catch (RuntimeException e) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting core service", e);
}
... ...
LockSettingsService // 屏幕锁定服务,管理每个用户的相关锁屏信息
DeviceIdleController // Doze模式的主要驱动
DevicePolicyManagerService // 提供一些系统级别的设置及属性
StatusBarManagerService // 状态栏管理服务
ClipboardService // 系统剪切板服务
NetworkManagementService // 网络管理服务
TextServicesManagerService // 文本服务,例如文本检查等
NetworkScoreService // 网络评分服务
NetworkStatsService // 网络状态服务
NetworkPolicyManagerService // 网络策略服务
WifiP2pService // Wifi Direct服务
WifiService // Wifi服务
WifiScanningService // Wifi扫描服务
RttService // Wifi相关
EthernetService // 以太网服务
ConnectivityService // 网络连接管理服务
NsdService // 网络发现服务
NotificationManagerService // 通知栏管理服务
DeviceStorageMonitorService // 磁盘空间状态检测服务
LocationManagerService // 位置服务,GPS、定位等
CountryDetectorService // 检测用户国家
SearchManagerService // 搜索管理服务
DropBoxManagerService // 用于系统运行时日志的存储于管理
WallpaperManagerService // 壁纸管理服务
AudioService // AudioFlinger的上层管理封装,主要是音量、音效、声道及铃声等的管理
DockObserver // 如果系统有个座子,当手机装上或拔出这个座子的话,就得靠他来管理了
WiredAccessoryManager // 监视手机和底座上的耳机
UsbService // USB服务
SerialService // 串口服务
TwilightService // 指出用户当前所在位置是否为晚上,被 UiModeManager 等用来调整夜间模式
BackupManagerService // 备份服务
AppWidgetService // 提供Widget的管理和相关服务
VoiceInteractionManagerService // 语音交互管理服务
DiskStatsService // 磁盘统计服务,供dumpsys使用
SamplingProfilerService // 用于耗时统计等
NetworkTimeUpdateService // 监视网络时间,当网络时间变化时更新本地时间。
CertBlacklister // 提供一种机制更新SSL certificate blacklist
DreamManagerService // 屏幕保护
PrintManagerService // 打印服务
HdmiControlService // HDMI控制服务
FingerprintService // 指纹服务
... ...
}
}
以上代码仅按顺序列出启动的服务,有些服务根据条件,如是否是工厂模式或系统属性配置,选择性启动,这里不考虑条件判断和异常处理。
自此,SystemServer 相关源码分析完毕。