目錄
第一篇:Android系統(tǒng)啟動之bootloader
第二篇:Android系統(tǒng)啟動之Init流程(上)
第三篇:Android系統(tǒng)啟動之Init流程(下)
第四篇:Android系統(tǒng)啟動之init.rc文件解析過程
第五篇:Android系統(tǒng)啟動之zyogte進(jìn)程
第六篇:Android系統(tǒng)啟動之zyogte進(jìn)程java(上)
第七篇:Android系統(tǒng)啟動之zyogte進(jìn)程java(下)
第八篇:Android系統(tǒng)啟動之SystemServer
SystemServer
首先看下什么是SystemServer?
SystemServer的進(jìn)程名實(shí)際上叫做“system_server”,通常簡稱為SS屹堰。
是系統(tǒng)中的服務(wù)駐留在其中,常見的比如WindowManagerServer(Wms)、ActivityManagerSystemService(AmS)忌怎、 PackageManagerServer(PmS)等傅是,這些系統(tǒng)服務(wù)都是以一個線程的方式存在于SystemServer進(jìn)程中岂丘。
SystemServer啟動
SystemServer是由Zygote啟動的.
源碼路徑frameworks/base/services/java/com/android/server/SystemServer.java
/**
* The main entry point from zygote.
*/
public static void main(String[] args) {
new SystemServer().run();
}
這樣SystemServer便啟動起來了.
run函數(shù)
我們來看下run
的實(shí)現(xiàn)
private void run() {
try {
traceBeginAndSlog("InitBeforeStartServices");
// 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.
//---------------------------------------------------------------
//-----------------------1.設(shè)定時(shí)間-------------------------------
//---------------------------------------------------------------
if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
Slog.w(TAG, "System clock is before 1970; setting to 1970.");
SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
}
//
// Default the timezone property to GMT if not set.
//
String timezoneProperty = SystemProperties.get("persist.sys.timezone");
if (timezoneProperty == null || timezoneProperty.isEmpty()) {
Slog.w(TAG, "Timezone not set; setting to GMT.");
SystemProperties.set("persist.sys.timezone", "GMT");
}
// If the system has "persist.sys.language" and friends set, replace them with
// "persist.sys.locale". Note that the default locale at this point is calculated
// using the "-Duser.locale" command line flag. That flag is usually populated by
// AndroidRuntime using the same set of system properties, but only the system_server
// and system apps are allowed to set them.
//
// NOTE: Most changes made here will need an equivalent change to
// core/jni/AndroidRuntime.cpp
//---------------------------------------------------------------
//-----------------------2.設(shè)定語言-------------------------------
//---------------------------------------------------------------
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", "");
}
// The system server should never make non-oneway calls
Binder.setWarnOnBlocking(true);
// Here we go!
Slog.i(TAG, "Entered the Android system server!");
int uptimeMillis = (int) SystemClock.elapsedRealtime();
EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, uptimeMillis);
if (!mRuntimeRestart) {
MetricsLogger.histogram(null, "boot_system_server_init", uptimeMillis);
}
// In case the runtime switched since last boot (such as when
// the old runtime was removed in an OTA), set the system
// property so that it is in sync. We can | xq oqi't do this in
// libnativehelper's JniInvocation::Init code where we already
// had to fallback to a different runtime because it is
// running as root and we need to be the system user to set
// the property. http://b/11463182
//---------------------------------------------------------------
//-----------------------3.虛擬機(jī)庫文件路徑 ---------------------
//---------------------------------------------------------------
SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
// 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);
}
// Mmmmmm... more memory!
//---------------------------------------------------------------
//-----------------------4.清除內(nèi)存使用上線 ---------------------
//---------------------------------------------------------------
VMRuntime.getRuntime().clearGrowthLimit();
// The system server has to run all of the time, so it needs to be
// as efficient as possible with its memory usage.
//設(shè)定內(nèi)存使用率
VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
// Some devices rely on runtime fingerprint generation, so make sure
// we've defined it before booting further.
//---------------------------------------------------------------
//-----------------------5.設(shè)定指紋使用 ------------------------
//---------------------------------------------------------------
Build.ensureFingerprintProperty();
// Within the system server, it is an error to access Environment paths without
// explicitly specifying a user.
//---------------------------------------------------------------
//-----------------------6.設(shè)定環(huán)境變量訪問用戶條件 --------------
//---------------------------------------------------------------
Environment.setUserRequired(true);
// Within the system server, any incoming Bundles should be defused
// to avoid throwing BadParcelableException.
BaseBundle.setShouldDefuse(true);
// Ensure binder calls into the system always run at foreground priority.
//---------------------------------------------------------------
//-----------------------7.設(shè)定binder服務(wù)永遠(yuǎn)運(yùn)行在前臺 ----------
//---------------------------------------------------------------
BinderInternal.disableBackgroundScheduling(true);
// Increase the number of binder threads in system_server
//---------------------------------------------------------------
//-----------------------8.設(shè)定線程池最大線程數(shù)-------------------
//---------------------------------------------------------------
BinderInternal.setMaxThreads(sMaxBinderThreads);
// Prepare the main looper thread (this thread).
android.os.Process.setThreadPriority(
android.os.Process.THREAD_PRIORITY_FOREGROUND);
android.os.Process.setCanSelfBackground(false);
Looper.prepareMainLooper();
// Initialize native services.
System.loadLibrary("android_servers");
// Check whether we failed to shut down last time we tried.
// This call may not return.
performPendingShutdown();
// Initialize the system context.
createSystemContext();
// Create the system service manager.
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
// Prepare the thread pool for init tasks that can be parallelized
SystemServerInitThreadPool.get();
} finally {
traceEnd(); // InitBeforeStartServices
}
// Start services.
//---------------------------------------------------------------
//-----------------------9.啟動各種服務(wù) ------------------------
//---------------------------------------------------------------
try {
traceBeginAndSlog("StartServices");
startBootstrapServices();
startCoreServices();
startOtherServices();
SystemServerInitThreadPool.shutdown();
} catch (Throwable ex) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting system services", ex);
throw ex;
} finally {
traceEnd();
}
// For debug builds, log event loop stalls to dropbox for analysis.
//---------------------------------------------------------------
//-----------------------10.debug模式開啟log ------------------
//---------------------------------------------------------------
if (StrictMode.conditionallyEnableDebugLogging()) {
Slog.i(TAG, "Enabled StrictMode for system server main thread.");
}
if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
int uptimeMillis = (int) SystemClock.elapsedRealtime();
MetricsLogger.histogram(null, "boot_system_server_ready", uptimeMillis);
final int MAX_UPTIME_MILLIS = 60 * 1000;
if (uptimeMillis > MAX_UPTIME_MILLIS) {
Slog.wtf(SYSTEM_SERVER_TIMING_TAG,
"SystemServer init took too long. uptimeMillis=" + uptimeMillis);
}
}
// Loop forever.
//---------------------------------------------------------------
//-----------------------11.服務(wù)開啟循環(huán) ------------------
//---------------------------------------------------------------
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
代碼中大致分為11個步驟:
1.設(shè)定時(shí)間
2.設(shè)定語言
3.虛擬機(jī)庫文件路徑
4.清除內(nèi)存使用上線
5.設(shè)定指紋使用
6.設(shè)定環(huán)境變量訪問用戶條件
7.設(shè)定binder服務(wù)永遠(yuǎn)運(yùn)行在前臺
8.設(shè)定線程池最大線程數(shù)
9.啟動各種服務(wù)
10.debug模式開啟log
11.服務(wù)開啟循環(huán)
啟動系統(tǒng)上下文
// Initialize the system context.
createSystemContext();
函數(shù)實(shí)現(xiàn)為base/services/java/com/android/server/SystemServer.java:475:
:
private void createSystemContext() {
//---------------------------------------------------------------
//-----------------------1.獲取ActivityThread對象 ------------------
//---------------------------------------------------------------
ActivityThread activityThread = ActivityThread.systemMain();
//---------------------------------------------------------------
//-----------------------2.獲取系統(tǒng)上下文 ------------------
//---------------------------------------------------------------
mSystemContext = activityThread.getSystemContext();
//---------------------------------------------------------------
//-----------------------3.設(shè)定系統(tǒng)主題 ------------------
//---------------------------------------------------------------
mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
final Context systemUiContext = activityThread.getSystemUiContext();
systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
}
代碼中大致分為3個步驟:
1.獲取ActivityThread對象
2.獲取系統(tǒng)上下文
3.設(shè)定系統(tǒng)主題
創(chuàng)建SystemServiceManage
// Create the system service manager.
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
構(gòu)造函數(shù)實(shí)現(xiàn)為base/services/core/java/com/android/server/SystemServiceManager.java
SystemServiceManager(Context context) {
mContext = context;
}
幾乎什么也沒做.
addService函數(shù)實(shí)現(xiàn)frameworks/base/core/java/com/android/server/LocalServices.java
/**
* Adds a service instance of the specified interface to the global registry of loca l services.
*/
public static <T> void addService(Class<T> type, T service) {
synchronized (sLocalServiceObjects) {
if (sLocalServiceObjects.containsKey(type)) {
throw new IllegalStateException("Overriding service registration");
}
sLocalServiceObjects.put(type, service);
}
}
參考
Android 內(nèi)核初識(6)SystemServer進(jìn)程
Android系統(tǒng)啟動——6 SystemServer啟動