参考文章
一、启动过程
frameworks/base/services/java/com.android.server.SystemServer.java。
public final class SystemServer {
public static void main(String[] args) {
new SystemServer().run();
}
private void run() {
//如果设备时间早于1970年很多API处理负数时会crash,所以直接设置为1970年1月1日
if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {...}
//未设置时区的话默认设为 GMT
if (timezoneProperty == null || timezoneProperty.isEmpty()) {...}
//语言地区设置
if (!SystemProperties.get("persist.sys.language").isEmpty()) {...}
//设置虚拟机运行库路径
SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
//确保指纹信息已经定义
Build.ensureFingerprintProperty();
//确保系统的 Binder 调用总是运行在前台优先级
BinderInternal.disableBackgroundScheduling(true);
//创建主线程 Looper
Looper.prepareMainLooper();
Looper.getMainLooper().setSlowLogThresholdMs(SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);
//初始化 native 服务,加载 libandroid_servers.so 库
System.loadLibrary("android_servers");
//初始化系统上下文
createSystemContext();
//创建系统服务管理 SystemServiceManager 并注册到 LocalServices 中
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
//准备任务的线程池
SystemServerInitThreadPool.get();
//启动系统引导服务
startBootstrapServices();
//启动系统核心服务
startCoreServices();
//启动其他服务
startOtherServices(); //最后会调用 AMS 的 onSystemReady() 方法启动桌面 Activity
//开启循环(主线程的启动工作完成,进入loop循环等待处理Handler发送的Message)
Looper.loop();
}
}
- 语言、时区、地区等设置
- 虚拟机内存设置
- 指纹信息,Binder 调用设置
- 创建主线程 Looper
- 初始化 native 服务,加载 libandroid_servers.so
- 初始化系统上下文
- 创建 SystemServiceManager
- 启动各种服务(引导服务、核心服务、其它服务)
- 开启 loop() 循环
二、初始化系统上下文
创建了系统的 ActivityThread 对象,运行环境mSystemContext、systemUiContext(会传入AMS中)并设置主题。
private void createSystemContext() {
//创建activityThread对象(此处并不是线程的概念,只是一个对象而已 )
ActivityThread activityThread = ActivityThread.systemMain();
//赋值系统上下文
mSystemContext = activityThread.getSystemContext();
//设置系统主题
mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
//赋值系统UI上下文
final Context systemUiContext = activityThread.getSystemUiContext();
//设置系统UI主题
systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
}
2.1 ActivityThread
Instrumentation | 优先其他类被初始化,系统先创建它,再通过它创建其他组件。允许检测系统与应用所有交互。应用AndroidManifest.xml标签定义实现。 |
Context | 是Android中的一个抽象类,用于维护应用运行环境的全局信息。通过Context可以访问应用的资源和类,甚至进行系统级操作,例如启动Activity,发送广播等。 |
Application | 保存应用的全局状态。 |
public static ActivityThread systemMain() {
ActivityThread thread = new ActivityThread();
thread.attach(true, 0); //传true是系统进程,false是应用进程
return thread;
}
private void attach(boolean system, long startSeq) {
if (!system) {
//应用进程的处理流程
} else {
//系统进程的处理流程(该情况只在SystemServer中处理)
//Instrumentation
mInstrumentation = new Instrumentation();
mInstrumentation.basicInit(this);
//Context
ContextImpl context = ContextImpl.createAppContext(this,getSystemContext().mPackageInfo);
//Application
mInitialApplication = context.mPackageInfo.makeApplication(true, null);
mInitialApplication.onCreate();
}
}
三、启动各种服务
通过 SystemServiceManager.startService() 启动各种系统服务,会回调系统服务的 onStart() 方法。当启动到某个阶段再通过 SystemServiceManager.startBootPhase() 遍历已启动的系统服务,会回调系统服务的 onBootPhase() 方法。
3.1 启动引导服务 startBootstrapServices()
Installer | 安装apk时的一个服务类。 |
ActivityManagerService | 四大组件的启动、切换、调度。 |
PowerManagerService | 系统中和Power相关的计算,然后决策系统应该如何反应。 |
LightsService | 管理和显示背光LED。 |
DisplayManagerService | 用来管理所有显示设备。 |
UserManagerService | 多用户模式管理。 |
SensorService | 传感器服务。 |
PackageManagerService | 对apk进行安装、解析、删除、卸载等等操作。 |
DeviceIdentifiersPolicyService | |
RecoverySystemService | |
StartSidekickService | |
OverlayManagerService |
private void startBootstrapServices() {
final String TAG_SYSTEM_CONFIG = "ReadingSystemConfig";
SystemServerInitThreadPool.get().submit(SystemConfig::getInstance, TAG_SYSTEM_CONFIG);
// 阻塞等待和 installer 建立 socket 连接,installer 断开会重连
Installer installer = mSystemServiceManager.startService(Installer.class);
// 启动 DeviceIdentifiersPolicyService,在 ActivityManagerService 之前
mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);
// 启动 ActivityManagerService
mActivityManagerService = mSystemServiceManager.startService(ActivityManagerService.Lifecycle.class).getService();
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer); //AMS 和 installer建立关系
// 启动 PowerManagerService
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
// 启动 RecoverySystemService
mSystemServiceManager.startService(RecoverySystemService.class);
// 启动 LightsService
mSystemServiceManager.startService(LightsService.class);
// 启动 DisplayManagerService,在 PackageManagerService 之前
mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
//100
mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
// 启动 PackageManagerService
mPackageManagerService = PackageManagerService.main(mSystemContext, installer, mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
mFirstBoot = mPackageManagerService.isFirstBoot();
mPackageManager = mSystemContext.getPackageManager();
if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
MetricsLogger.histogram(null, "boot_package_manager_init_ready",
(int) SystemClock.elapsedRealtime());
}
if (!mOnlyCore) {
boolean disableOtaDexopt = SystemProperties.getBoolean("config.disable_otadexopt",
false);
if (!disableOtaDexopt) {
traceBeginAndSlog("StartOtaDexOptService");
try {
OtaDexoptService.main(mSystemContext, mPackageManagerService);
} catch (Throwable e) {
reportWtf("starting OtaDexOptService", e);
} finally {
traceEnd();
}
}
}
// 启动 UserManagerService
mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
// 初始化属性 cache 以缓存包资源
AttributeCache.init(mSystemContext);
// 设置 AMS
mActivityManagerService.setSystemProcess();
// DisplayManagerService needs to setup android.display scheduling related policies
// since setSystemProcess() would have overridden policies due to setProcessGroup
mDisplayManagerService.setupSchedulerPolicies();
// 启动 OverlayManagerService
OverlayManagerService overlayManagerService = new OverlayManagerService(mSystemContext, installer);
mSystemServiceManager.startService(overlayManagerService);
// 在单独的线程中启动 SensorService
mSensorServiceStart = SystemServerInitThreadPool.get().submit(() -> {
TimingsTraceLog traceLog = new TimingsTraceLog(SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
startSensorService();
}, START_SENSOR_SERVICE);
}
3.2 启动核心服务 startCoreServices()
BatteryService | 管理电池相关的服务 |
UsageStatsService | 收集用户使用每一个APP的频率、使用时常 |
WebViewUpdateService | WebView更新服务 |
BinderCallsStatsService |
private void startCoreServices() {
// 启动服务 BatteryService,需要 LightService
mSystemServiceManager.startService(BatteryService.class);
// 启动服务 UsageStatsService,统计应用使用情况
mSystemServiceManager.startService(UsageStatsService.class);
mActivityManagerService.setUsageStatsManager(
LocalServices.getService(UsageStatsManagerInternal.class));
// 检查是否存在可更新的 WebView。存在就启动服务 WebViewUpdateService
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_WEBVIEW)) {
mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
}
// 启动服务 BinderCallsStatsService,跟踪 Binder 调用的 cpu 时间消耗
BinderCallsStatsService.start();
}
3.3 启动其他服务 startOtherServices()
CameraService | 摄像头相关服务 |
AlarmManagerService | 全局定时器管理服务 |
InputManagerService | 管理输入事件 |
WindowManagerService | 窗口管理服务 |
VrManagerService | VR模式管理服务 |
BluetoothService | 蓝牙管理服务 |
NotificationManagerService | 通知管理服务 |
DeviceStorageMonitorService | 存储相关管理服务 |
LocationManagerService | 定位管理服务 |
AudioService | 音频相关管理服务 |
...60多种 | ... |
private void startOtherServices(){
KeyAttestationApplicationIdProviderService/KeyChainSystemService
SchedulingPolicyService/TelecomLoaderService/TelephonyRegistry
mContentResolver = context.getContentResolver();
AccountManagerService/ContentService
mActivityManagerService.installSystemProviders();
DropBoxManagerService/VibratorService/ConsumerIrService/AlarmManagerService
final Watchdog watchdog = Watchdog.getInstance();
watchdog.init(context, mActivityManagerService);
InputManagerService/WindowManagerService/VrManagerService/BluetoothService
IpConnectivityMetrics/NetworkWatchlistService/PinnerService
InputMethodManagerService/AccessibilityManagerService/StorageManagerService
StorageStatsService/UiModeManagerService/LockSettingsService
PersistentDataBlockService/OemLockService/DeviceIdleController
DevicePolicyManagerService/StatusBarManagerService/ClipboardService
NetworkManagementService/IpSecService/TextServicesManagerService
TextClassificationManagerService/NetworkScoreService/NetworkStatsService
NetworkPolicyManagerService/WifiScanningService/RttService
WifiAware/WifiP2P/Lowpan/Ethernet/ConnectivityService/NsdService
SystemUpdateManagerService/UpdateLockService/NotificationManagerService
DeviceStorageMonitorService/LocationManagerService/CountryDetectorService
SearchManagerService/WallpaperManagerService/AudioService/BroadcastRadioService
DockObserver/ThermalObserver/WiredAccessoryManager/MidiManager/UsbService
SerialService/HardwarePropertiesManagerService/TwilightService
ColorDisplayService/JobSchedulerService/SoundTriggerService/TrustManagerService
BackupManager/AppWidgerService/VoiceRecognitionManager/GestureLauncherService
SensorNotificationService/ContextHubSystemService/DiskStatsService
TimeZoneRulesManagerService/NetworkTimeUpdateService/CommonTimeManagementService
CertBlacklister/EmergencyAffordanceService/DreamManagerService/GraphicsStatsService
CoverageService/PrintManager/CompanionDeviceManager/RestrictionsManagerService
MediaSessionService/MediaUpdateService/HdmiControlService/TvInputManagerService
MediaResourceMonitorService/TvRemoteService/MediaRouterService/FingerprintService
BackgroundDexOptService/PruneInstantAppsJobService/ShortcutService
LauncherAppsService/CrossProfileAppsService/MediaProjectionManagerService
WearConfigService/WearConnectivityService/WearTimeService/WearLeftyService
WearGlobalActionsService/SliceManagerService/CameraServiceProxy/IoTSystemService
MmsServiceBroker/AutoFillService
// It is now time to start up the app processes...
vibrator.systemReady();
lockSettings.systemReady();
// 480
mSystemServiceManager.startBootPhase(SystemService.PHASE_LOCK_SETTINGS_READY);
// 500
mSystemServiceManager.startBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);
wm.systemReady();
mPowerManagerService.systemReady(mActivityManagerService.getAppOpsService());
mPackageManagerService.systemReady();
mDisplayManagerService.systemReady(safeMode, mOnlyCore);
// Start device specific services
final String[] classes = mSystemContext.getResources().getStringArray(R.array.config_deviceSpecificSystemServices);
for (final String className : classes) {
try {
mSystemServiceManager.startService(className);
} catch (Throwable e) {
reportWtf("starting " + className, e);
}
}
// 520
mSystemServiceManager.startBootPhase(SystemService.PHASE_DEVICE_SPECIFIC_SERVICES_READY);
//所有的服务都启动完毕,开始启动桌面
mActivityManagerService.systemReady(() -> {
// 550
mSystemServiceManager.startBootPhase(SystemService.PHASE_ACTIVITY_MANAGER_READY);
webviewPrep = SystemServerInitThreadPool.get().submit(() -> {...} //启动webview
startSystemUi(context, windowManagerF); //启动SystemUI
networkManagementF.systemReady();
ipSecServiceF.systemReady();
networkStatsF.systemReady();
connectivityF.systemReady();
Watchdog.getInstance().start
mPackageManagerService.waitForAppDataPrepared(); //等待所有的app data准备好
// 600
mSystemServiceManager.startBootPhase(SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
locationF.systemRunning();
countryDetectorF.systemRunning();
networkTimeUpdaterF.systemRunning();
commonTimeMgmtServiceF.systemRunning();
inputManagerF.systemRunning();
telephonyRegistryF.systemRunning();
mediaRouterF.systemRunning();
mmsServiceF.systemRunning();
incident.systemRunning();
}
}
四、SystemServiceManager
frameworks/base/services/core/java/com.android.server.SystemServiceManager.java
用来启动并管理系统服务,这个系统服务必须是 SystemService 的子类。
public final class SystemServiceManager implements Dumpable {
private List<SystemService> mServices; //记录类实例
private Set<String> mServiceClassnames; //记录类名
public <T extends SystemService> T startService(Class<T> serviceClass) {
final String name = serviceClass.getName(); //获取服务名称
//确保启动的服务是SystemService的子类
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);
}
startService(service); //调用同名重载
return service;
}
public void startService(final SystemService service) {
//查询,启动过就不会再启动
if (mServiceClassnames.contains(className)) {
return;
}
mServiceClassnames.add(className); //将服务名添加到集合中
mServices.add(service); //将服务实例添加到集合中
//回调服务的 onStart() 方法
service.onStart();
}
public void startBootPhase(final int phase) {
//循环遍历mService服务集合,回调服务的 onBootPhase() 方法
for (int i = 0; i < serviceLen; i++) {
final SystemService service = mServices.get(i);
service.onBootPhase(mCurrentPhase);
}
}
4.1 SystemService
frameworks/base/services/core/java/com.android.server.SystemService.java
系统服务往往自身或内部类(Lifecycle)继承于SystemService,复写抽象方法 onStart() 用于启动服务,也是SystemServiceManager启动服务时会回调的地方,复写抽象方法 onBootPhase() 用于系统服务启动到不同阶段时被回调。绝大部分系统服务会在 onStart() 中调用 publishBinderService() 注册用于进程间通信(底层是注册到 ServiceManager),或者调用 publishLocalService() 注册用于 SystemServer 进程本地通信(底层是注册到 LocalService)。
public abstract class SystemService {
//子类复写用于启动服务,也是SystemServiceManager启动服务时会回调的地方
public abstract void onStart();
//子类复写用于系统服务启动到不同阶段时被回调
public void onBootPhase( int phase) {}
//用于进程间通信
protected final void publishBinderService(String name, IBinder service, boolean allowIsolated, int dumpPriority) {
ServiceManager.addService(name, service, allowIsolated, dumpPriority);
}
//用于 SystemServer 进程中本地通信
protected final <T> void publishLocalService(Class<T> type, T service) {
LocalServices.addService(type, service);
}
}
//例如AMS中
public static final class Lifecycle extends SystemService {
private final ActivityManagerService mService;
public Lifecycle(Context context) {
super(context);
mService = new ActivityManagerService(context, sAtm);
}
@Override
public void onStart() {
mService.start();
}
@Override
public void onBootPhase(int phase) {
//判断不同阶段
if (phase == PHASE_SYSTEM_SERVICES_READY) {
mService.mBatteryStatsService.systemServicesReady();
mService.mServices.systemServicesReady();
} else if (phase == PHASE_ACTIVITY_MANAGER_READY) {
mService.startBroadcastObservers();
} else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
mService.mPackageWatchdog.onPackagesReady();
}
}
}
4.2 startService()
普遍的单个服务启动流程:
- 通过 startService() 根据传入的 Class 反射创建服务实例。
- 通过 mServices.add(记录实例) 和 mServiceClassnames.add(记录类名) 将服务注册到列表中。
- 回调服务的 onStart() 启动服务。
//例如Installer中
@Override
public void onStart() {
if (mIsolated) {
mInstalld = null;
} else {
connect();
}
}
//例如AMS中
@Override
public void onStart() {
mService.start();
}
//例如BatteryService中
@Override
public void onStart() {
registerHealthCallback();
mBinderService = new BinderService();
publishBinderService("battery", mBinderService);
mBatteryPropertiesRegistrar = new BatteryPropertiesRegistrar();
publishBinderService("batteryproperties", mBatteryPropertiesRegistrar);
publishLocalService(BatteryManagerInternal.class, new LocalService());
}
4.3 startBootPhas()
会根据当前系统启动到不同阶段回调已经添加到成员变量 mServices 的所有系统服务的 onBootPhase() 方法,用于在合适的阶段做一些合适的事情,解决服务启动过程中的依赖问题。文章来源:https://www.toymoban.com/news/detail-502467.html
阶段分布位置 | 阶段名称 | 值 | 说明 |
startBootstrapServices() | PHASE_WAIT_FOR_DEFAULT_DISPLAY | 100 | 启动阶段 |
startOtherServices() | PHASE_LOCK_SETTINGS_READY | 480 | 之后服务可以获得锁定设置数据 |
PHASE_SYSTEM_SERVICES_READY | 500 | 之后可以安全的调用核心服务 | |
PHASE_DEVICE_SPECIFIC_SERVICES_READY | 520 | 之后可以安全调用设备特定服务 | |
PHASE_ACTIVITY_MANAGER_READY | 550 | 之后服务可以广播 | |
PHASE_THIRD_PARTY_APPS_CAN_START | 600 | 之后服务可以启动/绑定第三方应用,应用此时可以进行 Binder 调用 | |
AMS的finishBooting() | PHASE_BOOT_COMPLETED | 1000 | 之后允许用户和设备交互。这个阶段发生在启动完成,home 应用已经开始。系统服务更倾向于监听这个阶段,而不是监听启动广播 ACTION_BOOT_COMPLETED,以降低延迟 |
五、LocalService
SystemServer进程中各种系统服务提供的本地服务,将 LocalService 类比成缓存池,各种系统服务都可以通过 addService() 往里面存放对象,其它服务通过 getService() 就可以拿到对象访问了,使得系统服务之间弱耦合。文章来源地址https://www.toymoban.com/news/detail-502467.html
到了这里,关于Framework - SystemServer的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!