type
status
date
slug
summary
tags
category
icon
password
app_process64在启动zygote进程的时候,会从zygote进程fork出system_server进程.
system_server的入口在SystemServer.java中

SystemServer

// 切换runtime,即dalvik 还是 art SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary()); Looper.prepareMainLooper(); // 初始化native service System.loadLibrary("android_servers"); // 初始化系统context. createSystemContext(); // 创建 system service manager. 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(); // 启动service startBootstrapServices(); startCoreServices(); startOtherServices(); Looper.loop();
从上面的代码可以看出来,system_server主要做了下面这些事:
  1. 加载libandroid_servers.so
  1. 创建系统Context
  1. 创建SystemServiceManager,并添加到LocalServices中
  1. 依次启动启动服务,核心服务,和一些其他服务
  1. 在当前线程开启Looper机制

加载libandroid_servers.so

查看frameworks/base/services/Android.bp:
cc_library_shared { name: "libandroid_servers", defaults: ["libservices.core-libs"], whole_static_libs: ["libservices.core"], }
可知libservices.core中的所有内容会链接到libandroid_servers中,而 libservices.coreframeworks/base/services/core/jni/下多个JNI文件:
cc_library_static { name: "libservices.core", defaults: ["libservices.core-libs"], srcs: [ "BroadcastRadio/JavaRef.cpp", "BroadcastRadio/NativeCallbackThread.cpp", "BroadcastRadio/BroadcastRadioService.cpp", "BroadcastRadio/Tuner.cpp", "BroadcastRadio/TunerCallback.cpp", "BroadcastRadio/convert.cpp", "BroadcastRadio/regions.cpp", "com_android_server_AlarmManagerService.cpp", "com_android_server_adb_AdbDebuggingManager.cpp", "com_android_server_am_BatteryStatsService.cpp", "com_android_server_connectivity_Vpn.cpp", "com_android_server_ConsumerIrService.cpp", "com_android_server_devicepolicy_CryptoTestHelper.cpp", "com_android_server_HardwarePropertiesManagerService.cpp", "com_android_server_input_InputManagerService.cpp", "com_android_server_lights_LightsService.cpp", "com_android_server_location_GnssLocationProvider.cpp", "com_android_server_locksettings_SyntheticPasswordManager.cpp", "com_android_server_net_NetworkStatsService.cpp", "com_android_server_power_PowerManagerService.cpp", "com_android_server_security_VerityUtils.cpp", "com_android_server_SerialService.cpp", "com_android_server_storage_AppFuseBridge.cpp", "com_android_server_SystemServer.cpp", "com_android_server_TestNetworkService.cpp", "com_android_server_tv_TvUinputBridge.cpp", "com_android_server_tv_TvInputHal.cpp", "com_android_server_vr_VrManagerService.cpp", "com_android_server_UsbAlsaJackDetector.cpp", "com_android_server_UsbDeviceManager.cpp", "com_android_server_UsbDescriptorParser.cpp", "com_android_server_UsbMidiDevice.cpp", "com_android_server_UsbHostManager.cpp", "com_android_server_VibratorService.cpp", "com_android_server_PersistentDataBlockService.cpp", "com_android_server_GraphicsStatsService.cpp", "com_android_server_am_AppCompactor.cpp", "com_android_server_am_LowMemDetector.cpp", "onload.cpp", ":lib_networkStatsFactory_native", ], include_dirs: [ "frameworks/base/libs", "frameworks/native/services", "system/gatekeeper/include", ], header_libs: [ "bionic_libc_platform_headers", ], } cc_defaults { name: "libservices.core-libs", shared_libs: [ "libadb_pairing_server", "libadb_pairing_connection", "libandroid_runtime", "libandroidfw", "libaudioclient", "libbase", "libappfuse", "libbinder", "libcutils", "libcrypto", "liblog", "libhardware", "libhardware_legacy", "libhidlbase", "libkeystore_binder", "libmtp", "libnativehelper", "libutils", "libui", "libinput", "libinputflinger", "libinputflinger_base", "libinputservice", "libschedulerservicehidl", "libsensorservice", "libsensorservicehidl", "libstatshidl", "libgui", "libusbhost", "libtinyalsa", "libEGL", "libGLESv2", "libnetutils", "libhidlbase", "libutils", "libhwui", "libbpf_android", "libnetdbpf", "libnetdutils", "libpsi", "android.hardware.audio.common@2.0", "android.hardware.broadcastradio@1.0", "android.hardware.broadcastradio@1.1", "android.hardware.contexthub@1.0", "android.hardware.gnss@1.0", "android.hardware.gnss@1.1", "android.hardware.gnss@2.0", "android.hardware.gnss.measurement_corrections@1.0", "android.hardware.gnss.visibility_control@1.0", "android.hardware.input.classifier@1.0", "android.hardware.ir@1.0", "android.hardware.light@2.0", "android.hardware.power@1.0", "android.hardware.power@1.1", "android.hardware.power.stats@1.0", "android.hardware.thermal@1.0", "android.hardware.tv.input@1.0", "android.hardware.vibrator-cpp", "android.hardware.vibrator@1.0", "android.hardware.vibrator@1.1", "android.hardware.vibrator@1.2", "android.hardware.vibrator@1.3", "android.hardware.vr@1.0", "android.frameworks.schedulerservice@1.0", "android.frameworks.sensorservice@1.0", "android.frameworks.stats@1.0", "android.system.suspend@1.0", "suspend_control_aidl_interface-cpp", ], static_libs: [ "android.hardware.broadcastradio@common-utils-1x-lib", ], product_variables: { arc: { shared_libs: [ "libarcbridge", "libarcbridgeservice", "libarctimer", "libbase", "libcap", "libchrome", "libmojo", ], } } }
因此,这个so其实包含了frameworks/base/services/core/jni/下的内容.并且依赖了一些基础的so文件.

创建SystemContext 和SystemUiContext

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); }
笼统的说,这个方法主要就是为了创建SystemContext和SystemUiContext. SystemContext和SystemUiContext都是ContextImpl对象,并且都是单例. 这里创建的SystemContext与SystemUiContext共享相同的LoadedApk,即context中的packageInfo.
这里创建ActivityThread的时候,会判断机型,如果是低端机,就禁止使用Thread Renderer:
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); return thread; }
attach的过程如下:
private void attach(boolean system, long startSeq) { sCurrentActivityThread = this; mSystemThread = system; if (!system) { // 非system进程时执行这个分支 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>", UserHandle.myUserId()); RuntimeInit.setApplicationObject(mAppThread.asBinder()); final IActivityManager mgr = ActivityManager.getService(); try { mgr.attachApplication(mAppThread, startSeq); } catch (RemoteException ex) { throw ex.rethrowFromSystemServer(); } // Watch for getting close to heap limit. BinderInternal.addGcWatcher(new Runnable() { @Override public void run() { if (!mSomeActivitiesChanged) { return; } Runtime runtime = Runtime.getRuntime(); long dalvikMax = runtime.maxMemory(); long dalvikUsed = runtime.totalMemory() - runtime.freeMemory(); if (dalvikUsed > ((3*dalvikMax)/4)) { if (DEBUG_MEMORY_TRIM) Slog.d(TAG, "Dalvik max=" + (dalvikMax/1024) + " total=" + (runtime.totalMemory()/1024) + " used=" + (dalvikUsed/1024)); mSomeActivitiesChanged = false; try { ActivityTaskManager.getService().releaseSomeActivities(mAppThread); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } } } }); } else { // system_server进程时执行这个分支 android.ddm.DdmHandleAppName.setAppName("system_process", UserHandle.myUserId()); try { mInstrumentation = new Instrumentation(); mInstrumentation.basicInit(this); ContextImpl context = ContextImpl.createAppContext( this, getSystemContext().mPackageInfo); mInitialApplication = context.mPackageInfo.makeApplication(true, null); 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); }
ActiviyThread的主要作用是:
  • 管理应用进程的主线程执行
  • 调度,执行activity,broadcast和其他操作
attach的这个操作会创建一个AppContext(其实也是ContextImpl对象),并通过LoadedApk创建一个默认的Application(android.app.Application).

创建SystemServiceManager

创建SystemServiceManager,然后将其添加到一个Map中,后续统一处理.

启动各种服务

分成三类服务:
  • BootStrap
  • Core
  • Other
所有服务均是SystemService的实现类,通过SystemServiceManager启动服务的时候,会调用service的onStart()方法启动服务.

Bootstrap Service

  • WatchDog 其实就是一个Thread对象,当启动过程中发生死锁,可以使system_server崩溃
  • Installer 使用之前创建的SystemServiceManager对象启动Installer Service. Installer service在启动的时候会通过Binder机制请求installd(一个守护进程,用于安装apk)
  • DeviceIdentifiersPolicyService 定义访问设备标识符的策略
  • UriGrantsManagerService.LifeCyle 管理Uri授权
  • ActivityTaskManagerService.Lifecycle 管理Activity和Activity的容器,比如task, stacks, displays等
  • ActivityManagerService
  • PowerManagerService
  • ThermalManagerService
  • RecoverySystemService
  • LightsService
  • SidekickService
  • DisplayManagerService
  • UserManagerService
  • OverlayManagerService
  • SensorPrivacyService

Core Service

  • BatteryService
  • UsageStatsService
  • WebViewUpdateService
  • CachedDeviceStateService
  • BinderCallsStatsService.LifeCycle
  • RollbackManagerService
  • BugreportManagerService
  • GpuService

Other Service

  • VibratorService
  • DynamicSystemService
  • NetworkManagementService
  • IpSecService
  • NetworkStatsService
  • NetworkPolicyManagerService
  • ConnectivityService
  • NsdService
  • WindowManagerService
  • SerialService
  • NetworkTimeUpdateService
  • InputManagerService
  • ConsumerIrService
  • HardwarePropertiesManagerService
  • UiModeManagerService
  • ContentCaptureService
  • AttentionService
  • SystemCaptionsManagerService
  • AdbService
  • PermissionPolicyService ...
在启动Other类服务的最后阶段会执行mActivityManagerService.systemReady() 这个方法中会执行一些方法的systemReady方法,并启动System UI.

启动System UI

private static void startSystemUi(Context context, WindowManagerService windowManager) { Intent intent = new Intent(); intent.setComponent(new ComponentName("com.android.systemui", "com.android.systemui.SystemUIService")); intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING); //Slog.d(TAG, "Starting service: " + intent); context.startServiceAsUser(intent, UserHandle.SYSTEM); windowManager.onSystemUiStarted(); }
有关System UI相关的内容可以参考:
Android系统启动流程-Zygote分析Android系统启动流程-Native方法的注册
姜康
姜康
一个软件工程师
公告
type
status
date
slug
summary
tags
category
icon
password
🎉博客网站重新制作了🎉
👏欢迎更新体验👏