首页 > 代码库 > SystemServer源码分析
SystemServer源码分析
从SystemServer的main函数入手
/**
* The main entry point from zygote.
*/
public static void main(String[] args) {
new SystemServer().run();
}
这里创建了一个SystemServer并调用了它的run()函数,进入run()函数,这个方法内部比较多,分段分析:
时间处理
// If a device‘s clock is before 1970 (before 0), a lot of
// APIs crash dealing with negative numbers, notably
// java.io.File#setLastModified, so instead we fake it and
// hope that time from cell towers or NTP fixes it shortly.
if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
Slog.w(TAG, "System clock is before 1970; setting to 1970.");
SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
}
一些API使用负数的时间时会导致异常,因此我们先在这里进行处理
性能统计
// Enable the sampling profiler.
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);
}
使用一个Timer每个小时执行一次writeSnapshot方法,进入到该方法中:
public static void writeSnapshot(final String processName, final PackageInfo packageInfo) {
if (!enabled) {
return;
}
if (samplingProfiler == null) {
Log.e(TAG, "SamplingProfilerIntegration is not started");
return;
}
if (pending.compareAndSet(false, true)) {
snapshotWriter.execute(new Runnable() {
public void run() {
try {
writeSnapshotFile(processName, packageInfo);
} finally {
pending.set(false);
}
}
});
}
}
snapshotWriter是什么?通过SamplingProfilerIntegration中的静态代码块可以知道,snapshotWriter是一个的线程池,每次只有一个线程执行队列中的任务
snapshotWriter = Executors.newSingleThreadExecutor(new ThreadFactory() {
public Thread newThread(Runnable r) {
return new Thread(r, TAG);
}
});
继续进入到writeSnapshotFile方法
private static void writeSnapshotFile(String processName, PackageInfo packageInfo) {
if (!enabled) {
return;
}
samplingProfiler.stop();
/*
* We use the global start time combined with the process name
* as a unique ID. We can‘t use a counter because processes
* restart. This could result in some overlap if we capture
* two snapshots in rapid succession.
*/
String name = processName.replaceAll(":", ".");
String path = SNAPSHOT_DIR + "/" + name + "-" + startMillis + ".snapshot";
long start = System.currentTimeMillis();
OutputStream outputStream = null;
try {
outputStream = new BufferedOutputStream(new FileOutputStream(path));
PrintStream out = new PrintStream(outputStream);
generateSnapshotHeader(name, packageInfo, out);
if (out.checkError()) {
throw new IOException();
}
BinaryHprofWriter.write(samplingProfiler.getHprofData(), outputStream);
} catch (IOException e) {
Log.e(TAG, "Error writing snapshot to " + path, e);
return;
} finally {
IoUtils.closeQuietly(outputStream);
}
// set file readable to the world so that SamplingProfilerService
// can put it to dropbox
new File(path).setReadable(true, false);
long elapsed = System.currentTimeMillis() - start;
Log.i(TAG, "Wrote snapshot " + path + " in " + elapsed + "ms.");
samplingProfiler.start(samplingProfilerMilliseconds);
}
主要就是将性能统计信息以文件保存在SNAPSHOT_DIR目录中,每个文件的命名规则为:name + “-” + startMillis + “.snapshot”
初始化android_services
// Initialize native services.
System.loadLibrary("android_servers");
/**
* Called to initialize native system services.
*/
nativeInit();
nativeInit方法为navite方法,为libandroid_servers.so里边的方法
初始化主线程的Looper
/**
* Initialize the current thread as a looper, marking it as an
* application‘s main looper. The main looper for your application
* is created by the Android environment, so you should never need
* to call this function yourself. See also: {@link #prepare()}
*/
Looper.prepareMainLooper();
初始化system context
// Initialize the system context.
createSystemContext();
private void createSystemContext() {
ActivityThread activityThread = ActivityThread.systemMain();
mSystemContext = activityThread.getSystemContext();
mSystemContext.setTheme(android.R.style.Theme_DeviceDefault_Light_DarkActionBar);
}
首先,看看ActivityThread是什么?
/**
* This manages the execution of the main thread in an
* application process, scheduling and executing activities,
* broadcasts, and other operations on it as the activity
* manager requests.
*
* {@hide}
*/
大概原意:管理着某个应用程序进程的主线程中的执行,包括:调度和执行activitys、broadcast和其他由ActivityManager请求的操作
这里主要做了三步操作:
- 调用systemMain方法,创建一个ActivityThread
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()) {
HardwareRenderer.disable(true);
} else {
HardwareRenderer.enableForegroundTrimming();
}
ActivityThread thread = new ActivityThread();
thread.attach(true);
return thread;
}
- 通过ActivityManager.isHighEndGfx()判断是否运行在大内存的设备中:假如是,则开启硬件加速;否则关闭
- 创建一个ActivityThread,并调用其attath方法
private void attach(boolean system) {
sCurrentActivityThread = this;
mSystemThread = system;
if (!system) {
......
......
// 省略部分代码
} else {
android.ddm.DdmHandleAppName.setAppName("system_process",
UserHandle.myUserId());
try {
mInstrumentation = new Instrumentation();
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);
}
}
// add dropbox logging to libcore
DropBox.setReporter(new DropBoxReporter());
ViewRootImpl.addConfigCallback(new ComponentCallbacks2() {
@Override
public void onConfigurationChanged(Configuration newConfig) {
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(newConfig, null)) {
// This actually changed the resources! Tell
// everyone about it.
if (mPendingConfiguration == null ||
mPendingConfiguration.isOtherSeqNewer(newConfig)) {
mPendingConfiguration = newConfig;
sendMessage(H.CONFIGURATION_CHANGED, newConfig);
}
}
}
}
@Override
public void onLowMemory() {
}
@Override
public void onTrimMemory(int level) {
}
});
}
- Instrumentation:创建该类的实例,该类用于监控该应用与系统之间的交互
- 调用ContextImpl.createAppContext()创建一个ContextImpl
- 调用context.mPackageInfo.makeApplication(true, null)创建该应用的Application对象,并调用该Application的onCreate()方法:这里启动了一个包名为android的系统应用程序
设置监听配置更新的回调
- 回到createSystemContext()方法,创建了ActivityThread之后,获取ContextImpl的引用,并保存在本地
mSystemContext = activityThread.getSystemContext();
public ContextImpl getSystemContext() {
synchronized (this) {
if (mSystemContext == null) {
mSystemContext = ContextImpl.createSystemContext(this);
}
return mSystemContext;
}
}
- 调用ContextImpl的setTheme()方法设置默认主题
回到SystemServer的run()方法,接着往下看
// Create the system service manager.
mSystemServiceManager = new SystemServiceManager(mSystemContext);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
- 创建一个SystemServiceManager对象
- 将该对象添加到LocalServices中
LocalServices类似与ServiceManger,但在这里注册的services不属于Binder对象,而且只能在该进程中有效
启动一系列的服务
// Start services.
try {
startBootstrapServices();
startCoreServices();
startOtherServices();
} catch (Throwable ex) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting system services", ex);
throw ex;
}
这里分开三个部分启动services
1 startBootstrapServices()
// 先看下官方对这个方法的说明
/**
* 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.
*/
大概原意是:在这个方法里边启动一些琐碎但重要的services,这些服务支持着system正常的运行。它们由于相互依赖紧密,因此需要在同一个地方进行初始化。除非你的服务也跟它们有着紧密依赖,否则就应该在其他的方法进行初始化
- Installer:
// Wait for installd to finish starting up so that it has a chance to
// create critical directories such as /data/user with the appropriate
// permissions. We need this to complete before we initialize other services.
mInstaller = mSystemServiceManager.startService(Installer.class);
这里通过mSystemServiceManager.startService()方法创建了一个Installer,并执行它的onStart()方法
private final InstallerConnection mInstaller;
@Override
public void onStart() {
Slog.i(TAG, "Waiting for installd to be ready.");
ping();
}
public boolean ping() {
if (mInstaller.execute("ping") < 0) {
return false;
} else {
return true;
}
}
public int execute(String cmd) {
String res = transact(cmd);
try {
return Integer.parseInt(res);
} catch (NumberFormatException ex) {
return -1;
}
}
public synchronized String transact(String cmd) {
if (!connect()) {
Slog.e(TAG, "connection failed");
return "-1";
}
if (!writeCommand(cmd)) {
/*
* If installd died and restarted in the background (unlikely but
* possible) we‘ll fail on the next write (this one). Try to
* reconnect and write the command one more time before giving up.
*/
Slog.e(TAG, "write command failed? reconnect!");
if (!connect() || !writeCommand(cmd)) {
return "-1";
}
}
if (LOCAL_DEBUG) {
Slog.i(TAG, "send: ‘" + cmd + "‘");
}
final int replyLength = readReply();
if (replyLength > 0) {
String s = new String(buf, 0, replyLength);
if (LOCAL_DEBUG) {
Slog.i(TAG, "recv: ‘" + s + "‘");
}
return s;
} else {
if (LOCAL_DEBUG) {
Slog.i(TAG, "fail");
}
return "-1";
}
}
上边的代码作用:InstallerConnection与installed通过LocalSocket链接,并通过‘ping’命令检查是否链接成功。***主要就是启动installed服务**
- ActivityManagerService
// Activity manager runs the show.
mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
private void start() {
// 清除所有的进程组
Process.removeAllProcessGroups();
// 启动用于统计CPU占用的Thread
mProcessCpuThread.start();
// 启动BatteryStatsService
mBatteryStatsService.publish(mContext);
// 启动AppOpsService
mAppOpsService.publish(mContext);
Slog.d("AppOps", "AppOpsService published");
// 将ActivityManagerService注册到LocalServices中
LocalServices.addService(ActivityManagerInternal.class, new LocalService());
}
上边的代码作用:启动一个ActivityManagerService,并将其注册到LocalServices中;并调用了ActivityManagerService的onStart()方法,并启动了其他一些服务
- PowerManagerService
// Power manager needs to be started early because other services need it.
// Native daemons may be watching for it to be registered so it must be ready
// to handle incoming binder calls immediately (including being able to verify
// the permissions for those calls).
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
// Now that the power manager has been started, let the activity manager
// initialize power management features.
mActivityManagerService.initPowerManagement();
其他服务可能需要使用到PowerManagerService,因此需要尽早的启动该服务。等它启动后,使用ActivityManagerService初始化电源管理功能
- DisplayManagerService
// Display manager is needed to provide display metrics before package manager
// starts up.
mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
显示管理器需要在包管理器启动前提供显示度量
- PackageManagerService
// Start the package manager.
Slog.i(TAG, "Package Manager");
mPackageManagerService = PackageManagerService.main(mSystemContext, mInstaller,
mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
mFirstBoot = mPackageManagerService.isFirstBoot();
mPackageManager = mSystemContext.getPackageManager();
启动PackageManagerService,在后边的文章再详细说明
- UserManagerService
Slog.i(TAG, "User Service");
ServiceManager.addService(Context.USER_SERVICE, UserManagerService.getInstance());
启动UserManagerService
- AttributeCache
// Initialize attribute cache used to cache resources from packages.AttributeCache.init(mSystemContext);
初始化AttributeCache用于缓存每个应用包的资源
- setSystemProcess
// Set up the Application instance for the system process and get started.
mActivityManagerService.setSystemProcess();
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));
ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
"android", STOCK_PM_FLAGS);
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);
mProcessNames.put(app.processName, app.uid, app);
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);
}
}
2 startCoreServices()
/**
* Starts some essential services that are not tangled up in the bootstrap process.
*/
private void startCoreServices() {
// Manages LEDs and display backlight.
mSystemServiceManager.startService(LightsService.class);
// Tracks the battery level. Requires LightService.
mSystemServiceManager.startService(BatteryService.class);
// Tracks application usage stats.
mSystemServiceManager.startService(UsageStatsService.class);
mActivityManagerService.setUsageStatsManager(
LocalServices.getService(UsageStatsManagerInternal.class));
// Tracks whether the updatable WebView is in a ready state and watches for update installs.
mSystemServiceManager.startService(WebViewUpdateService.class);
}
- LightsService:管理LED灯和背光灯的服务
- BatteryService:电源管理服务
- UsageStatsService:应用使用状跟踪服务
- WebView更新服务
3 startOtherServices()
private void startOtherServices() {
// 1. 根据配置启动一些相应的服务
// 2. Bring up services needed for UI.启动一些跟UI相关的services
// 3. 重点
mActivityManagerService.systemReady(new Runnable() {
@Override
public void run() {
Slog.i(TAG, "Making services ready");
mSystemServiceManager.startBootPhase(
SystemService.PHASE_ACTIVITY_MANAGER_READY);
try {
mActivityManagerService.startObservingNativeCrashes();
} catch (Throwable e) {
reportWtf("observing native crashes", e);
}
Slog.i(TAG, "WebViewFactory preparation");
WebViewFactory.prepareWebViewInSystemServer();
try {
startSystemUi(context);
} catch (Throwable e) {
reportWtf("starting System UI", e);
}
try {
if (mountServiceF != null) mountServiceF.systemReady();
} catch (Throwable e) {
reportWtf("making Mount Service ready", e);
}
try {
if (networkScoreF != null) networkScoreF.systemReady();
} catch (Throwable e) {
reportWtf("making Network Score Service ready", e);
}
try {
if (networkManagementF != null) networkManagementF.systemReady();
} catch (Throwable e) {
reportWtf("making Network Managment Service ready", e);
}
try {
if (networkStatsF != null) networkStatsF.systemReady();
} catch (Throwable e) {
reportWtf("making Network Stats Service ready", e);
}
try {
if (networkPolicyF != null) networkPolicyF.systemReady();
} catch (Throwable e) {
reportWtf("making Network Policy Service ready", e);
}
try {
if (connectivityF != null) connectivityF.systemReady();
} catch (Throwable e) {
reportWtf("making Connectivity Service ready", e);
}
try {
if (audioServiceF != null) audioServiceF.systemReady();
} catch (Throwable e) {
reportWtf("Notifying AudioService running", e);
}
Watchdog.getInstance().start();
// It is now okay to let the various system services start their
// third party code...
mSystemServiceManager.startBootPhase(
SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
try {
if (wallpaperF != null) wallpaperF.systemRunning();
} catch (Throwable e) {
reportWtf("Notifying WallpaperService running", e);
}
try {
if (immF != null) immF.systemRunning(statusBarF);
} catch (Throwable e) {
reportWtf("Notifying InputMethodService running", e);
}
try {
if (locationF != null) locationF.systemRunning();
} catch (Throwable e) {
reportWtf("Notifying Location Service running", e);
}
try {
if (countryDetectorF != null) countryDetectorF.systemRunning();
} catch (Throwable e) {
reportWtf("Notifying CountryDetectorService running", e);
}
try {
if (networkTimeUpdaterF != null) networkTimeUpdaterF.systemRunning();
} catch (Throwable e) {
reportWtf("Notifying NetworkTimeService running", e);
}
try {
if (commonTimeMgmtServiceF != null) {
commonTimeMgmtServiceF.systemRunning();
}
} catch (Throwable e) {
reportWtf("Notifying CommonTimeManagementService running", e);
}
try {
if (textServiceManagerServiceF != null)
textServiceManagerServiceF.systemRunning();
} catch (Throwable e) {
reportWtf("Notifying TextServicesManagerService running", e);
}
try {
if (atlasF != null) atlasF.systemRunning();
} catch (Throwable e) {
reportWtf("Notifying AssetAtlasService running", e);
}
try {
// TODO(BT) Pass parameter to input manager
if (inputManagerF != null) inputManagerF.systemRunning();
} catch (Throwable e) {
reportWtf("Notifying InputManagerService running", e);
}
try {
if (telephonyRegistryF != null) telephonyRegistryF.systemRunning();
} catch (Throwable e) {
reportWtf("Notifying TelephonyRegistry running", e);
}
try {
if (mediaRouterF != null) mediaRouterF.systemRunning();
} catch (Throwable e) {
reportWtf("Notifying MediaRouterService running", e);
}
try {
if (mmsServiceF != null) mmsServiceF.systemRunning();
} catch (Throwable e) {
reportWtf("Notifying MmsService running", e);
}
}
});
}
}
我们进入ActivityManagerService的systemReady()方法:
由于mSystemReady默认为false,因此Runnale的run()方法没有执行,而是执行了systemReady下边的代码:
......
......
// 省略部分代码
mBooting = true;
startHomeActivityLocked(mCurrentUserId);
在这里启动了第一个Activity,即Home
boolean startHomeActivityLocked(int userId) {
if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL
&& mTopAction == null) {
// We are running in factory test mode, but unable to find
// the factory test app, so just sit around displaying the
// error message and don‘t try to start anything.
return false;
}
Intent intent = getHomeIntent();
ActivityInfo aInfo =
resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
if (aInfo != null) {
intent.setComponent(new ComponentName(
aInfo.applicationInfo.packageName, aInfo.name));
// Don‘t do this if the home app is currently being
// instrumented.
aInfo = new ActivityInfo(aInfo);
aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
ProcessRecord app = getProcessRecordLocked(aInfo.processName,
aInfo.applicationInfo.uid, true);
if (app == null || app.instrumentationClass == null) {
intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
mStackSupervisor.startHomeActivity(intent, aInfo);
}
}
return true;
}
Intent getHomeIntent() {
Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
intent.setComponent(mTopComponent);
if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
intent.addCategory(Intent.CATEGORY_HOME);
}
return intent;
}
public static final String CATEGORY_HOME = "android.intent.category.HOME";
可以看到我们在AndroidManifest中配置要启动的Activity需要添加该”android.intent.category.HOME”category的原因,在这里可以体现
总结
至此,整个SystemServer的流程就分析完了,SystemServer内部主要就是启动一系列必要的系统services
SystemServer源码分析