您的位置:首页 > 移动开发 > Android开发

SystemServer分析

2017-02-11 14:33 295 查看

SystemServer

SystemServer
1createSystemContext
11systemMain

12getSystemContext
1121createSystemContext

2startBootstrapServices

21setSystemProcess

3startCoreServices

4startOtherServices

总结

那么大概又那些服务被启动了呢

SystemServer分成两个部分,一部分是由ZygoteInit进程启动,一部分执行SystemServer的main()方法启动

/**
* 这个主方法从zygote进程启动.
*/
public static void main(String[] args) {
new SystemServer().run();
}


接下来我们就开始分析SystemServer的run()方法

private void run() {
try {
...
//对于时间的处理
if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
Slog.w(TAG, "System clock is before 1970; setting to 1970.");
SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
}
...
//设置虚拟机库路径
SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
// 每个小时进行一次性能统计输出到文件中
if (SamplingProfilerIntegration.isEnabled()) {
SamplingProfilerIntegration.start();
mProfilerSnapshotTimer = new Timer();
mProfilerSnapshotTimer.schedule(new TimerTask() {
@Override
public void run() {
SamplingProfilerIntegration.writeSnapshot("system_server", null);
}
}, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
}
// Mmmmmm... more memory!
VMRuntime.getRuntime().clearGrowthLimit();
// 调整虚拟机堆内存
VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
...
//初始化主线程
Looper.prepareMainLooper();
// 装在libandroid_servers.so
// 注意在Android中库的名称都是lib+名称+.so
System.loadLibrary("android_servers");
...
// 创建ActivityThread并且创建系统的Context赋值给当前类变量mSystemContext
createSystemContext();//[1.1]
// 创建SystemServiceManager的对象,此对象负责系统Service的启动
mSystemServiceManager = new SystemServiceManager(mSystemContext);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
} finally {
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
// 创建启动所有的java服务
try {
Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartServices");
startBootstrapServices();//[1.2]
startCoreServices();.//[1.3]
startOtherServices();//[1.4]
} catch (Throwable ex) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting system services", ex);
throw ex;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
...
// 进入消息处理的循环
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}


小结下run方法中所做的重要的事情都有那些?

设置虚拟机库路径

初始化主线程

调整虚拟机堆内存

创建ActivityThread并且创建系统的ContextImpl赋值给当前类变量mSystemContext

创建SystemServiceManager的对象(此对象负责系统Service的启动)

创建启动所有的java服务

初始化主线程

进入消息处理的循环

1.1createSystemContext()

@(SystemServer.java->createSystemContext())

创建ActivityThread对象和ContextImpl对象

private void createSystemContext() {
ActivityThread activityThread = ActivityThread.systemMain();//[1.1.1]创建ActivityThread对象
mSystemContext = activityThread.getSystemContext();//[1.1.2]创建系统Context对象
mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
}


1.1.1systemMain()

@(ActivityThread.java->systemMain())

创建ActivityThread对象,这个对象主要是负责管理四大组件,ApplicationThread等等

public static ActivityThread systemMain() {
if (!ActivityManager.isHighEndGfx()) {
ThreadedRenderer.disable(true);
} else {
ThreadedRenderer.enableForegroundTrimming();
}
ActivityThread thread = new ActivityThread();//创建ActivityThread对象
thread.attach(true);
return thread;
}


1.1.2getSystemContext()

@(ActivityThread.java->getSystemContext())

public ContextImpl getSystemContext() {
synchronized (this) {
if (mSystemContext == null) {
mSystemContext = ContextImpl.createSystemContext(this);//[1.1.2.1]
}
return mSystemContext;
}
}


1.1.1.2.1createSystemContext()

@(ContextImpl.java->createSystemContext())

static ContextImpl createSystemContext(ActivityThread mainThread) {
LoadedApk packageInfo = new LoadedApk(mainThread);
ContextImpl context = new ContextImpl(null, mainThread,
packageInfo, null, null, 0, null, null, Display.INVALID_DISPLAY);//创建ContextImpl对象
context.mResources.updateConfiguration(context.mResourcesManager.getConfiguration(),
context.mResourcesManager.getDisplayMetrics());
return context;
}


1.2startBootstrapServices()

@(SystemServer.java->startBootstrapServices())

在这个方法中启动一些重要的service,这些服务支持system的正常运行,但是又互相依赖,所以放到SystemServer中进行集中初始化,如果自己的服务和这些服务有着密切的关系,要不然就要放到Installer中初始化.

private void startBootstrapServices() {
/*通过反射构造对象,并且调用将其添加到SystemServerManager中的ArrayList<SystemService>mServices中
并且调用对应的service.onStart()方法,因为所以service继承SystemService,其中需要实现onStart()方法*/
Installer installer = mSystemServiceManager.startService(Installer.class);
// 对AMS进行设置
mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);

// 电源管理服务,由于其他服务可能今早的需要电源的管理,所以电源管理服务在比较前面的位置
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
//...其他服务同理
// Only run "core" apps if we're encrypting the device.
String cryptState = SystemProperties.get("vold.decrypt");
...
//添加PMS服务并且运行
mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
mFirstBoot = mPackageManagerService.isFirstBoot();
mPackageManager = mSystemContext.getPackageManager();
...
//运行UMS
traceBeginAndSlog("StartUserManagerService");
mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
//用于缓存应用包资源
AttributeCache.init(mSystemContext);
mActivityManagerService.setSystemProcess();//[1.2.1]
startSensorService();
}


小结下startBootstrapServices方法中所做的重要的事情都有那些?

@(如果想写自己的系统服务就在这里进行添加)

创建ActivityManagerService

创建PowerManagerService,并初始化

创建DisplayManagerService,这里注意默认显示的必须在package manager之前初始化.

如果支持身份验证Service则支持身份验证

创建UserManagerService

随后通过AMS.setSystemProcess()添加启动一些一些Binder服务.

开启一些传感器服务

1.2.1setSystemProcess()

@(ActivityManagerService.java->setSystemProcess())

添加一些Service,ServiceManager.addService的原理在深入理解Android:卷2中仔细说明,目前本人未能彻底搞清楚Binder,所以在这里,只是指导将服务添加到native层就好.

public void setSystemProcess() {
try {
ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true);
ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
ServiceManager.addService("meminfo", new MemBinder(this));
ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
ServiceManager.addService("dbinfo", new DbBinder(this));
if (MONITOR_CPU_USAGE) {
ServiceManager.addService("cpuinfo", new CpuBinder(this));
}
ServiceManager.addService("permission", new PermissionController(this));
ServiceManager.addService("processinfo", new ProcessInfoService(this));

ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
"android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());

synchronized (this) {
ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0);
app.persistent = true;
app.pid = MY_PID;
app.maxAdj = ProcessList.SYSTEM_ADJ;
app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
synchronized (mPidsSelfLocked) {
mPidsSelfLocked.put(app.pid, app);
}
updateLruProcessLocked(app, false, null);
updateOomAdjLocked();
}
} catch (PackageManager.NameNotFoundException e) {
throw new RuntimeException(
"Unable to find android system package", e);
}
}


小结下setSystemProcess方法中所做的重要的事情都有那些?

@(如果想写自己的系统服务就在这里进行添加)

向ServiceManager中添加AMS

向ServiceManager中添加ProcessStatsService

向ServiceManager中添加MemBinder

向ServiceManager中添加GraphicsBinder

向ServiceManager中添加DbBinder

向ServiceManager中添加CpuBinder

向ServiceManager中添加ProcessInfoService

1.3startCoreServices()

@(SystemServer.java->startCoreServices())

启动一些核心服务

private void startCoreServices() {
// 启动电源管理服务
mSystemServiceManager.startService(BatteryService.class);
// 跟踪应用程序使用情况统计信息。
mSystemServiceManager.startService(UsageStatsService.class);
mActivityManagerService.setUsageStatsManager(
LocalServices.getService(UsageStatsManagerInternal.class));
//开启WebView更新服务
mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
}


1.4startOtherServices()

@(SystemServer.java->startOtherServices())

添加各式各样的服务之后调用systemReady来启动

private void startOtherServices() {
...
contentService = ContentService.main(context,
mFactoryTestMode == FactoryTest.FACTORY_TEST_LOW_LEVEL);
mActivityManagerService.installSystemProviders();
vibrator = new VibratorService(context);
ServiceManager.addService("vibrator", vibrator);
consumerIr = new ConsumerIrService(context);
ServiceManager.addService(Context.CONSUMER_IR_SERVICE, consumerIr);

mAlarmManagerService = mSystemServiceManager.startService(AlarmManagerService.class);
alarm = IAlarmManager.Stub.asInterface(
ServiceManager.getService(Context.ALARM_SERVICE));
final Watchdog watchdog = Watchdog.getInstance();
watchdog.init(context, mActivityManagerService);
...
mActivityManagerService.systemReady(new Runnable() {
@Override
public void run() {
Slog.i(TAG, "Making services ready");
mSystemServiceManager.startBootPhase(
SystemService.PHASE_ACTIVITY_MANAGER_READY);
Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "PhaseActivityManagerReady");

Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartObservingNativeCrashes");
try {
mActivityManagerService.startObservingNativeCrashes();
} catch (Throwable e) {
reportWtf("observing native crashes", e);
}
...
}
});
}


总结:

原来SystemServer开启了那么多系统的服务并且启动

- ActivityThread也是在此时创建的

- 主线程的Loop也是在这里创建的

- ContextImpl也是在这里创建的

- 创建你Application对象,并且调用对应的onCreate()方法

那么大概又那些服务被启动了呢?

EntropyService:熵(shang)服务,用于产生随机数

PowerManagerService:电源管理服务

ActivityManage搜索rService:最核心服务之一,Activity管理服务

TelephonyRegistry:电话服务,电话底层通知服务

PackageManagerService:程序包管理服务

AccountManagerService:联系人帐户管理服务

ContentService:内容提供器的服务,提供跨进程数据交换

LightsService:光感应传感器服务

BatteryService:电池服务,当电量不足时发广播

VibratorService:震动器服务

AlarmManagerService:闹钟服务

WindowManagerService:窗口管理服务

BluetoothService:蓝牙服务

InputMethodManagerService:输入法服务,打开关闭输入法

AccessibilityManagerService:辅助管理程序截获所有的用户输入,并根据这些输入给用户一些额外的反馈,起到辅助的效果,View的点击、焦点等事件分发管理服务

DevicePolicyManagerService:提供一些系统级别的设置及属性

StatusBarManagerService:状态栏管理服务

ClipboardService:粘贴板服务

NetworkManagementService:手机网络管理服务

TextServicesManagerService:

NetworkStatsService:手机网络状态服务

NetworkPolicyManagerService:

WifiP2pService:Wifi点对点直联服务

WifiService:WIFI服务

ConnectivityService:网络连接状态服务

ThrottleService:modem节流阀控制服务

MountService:磁盘加载服务,通常也mountd和vold服务结合

NotificationManagerService:通知管理服务,通常和StatusBarManagerService

DeviceStorageMonitorService:存储设备容量监听服务

LocationManagerService:位置管理服务

CountryDetectorService:检查当前用户所在的国家

SearchManagerService:搜索管理服务

DropBoxManagerService:系统日志文件管理服务(大部分程序错误信息)

WallpaperManagerService:壁纸管理服务

AudioService:AudioFlinger上层的封装的音量控制管理服务

UsbService:USB Host和device管理服务

UiModeManagerService:UI模式管理服务,监听车载、座机等场合下UI的变化

BackupManagerService:备份服务

AppWidgetService:应用桌面部件服务

RecognitionManagerService:身份识别服务

DiskStatsService:磁盘统计服务

SamplingProfilerService:性能统计服务

NetworkTimeUpdateService:网络时间更新服务
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Android系统