Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 開發核心解析:SystemServer 的啟動與服務註冊

編輯:關於 Android 開發

SystemServer 是 Android 系統中一個極為關鍵的核心進程,它由 zygote 進程所建立,因此在整個開機流程中僅次於 zygote。可以說,Android 絕大多數的系統服務循環都架構在 SystemServer 之上。在這個進程中,會看到系統建立了大部分服務,並透過 ServerManager 的 add_service 方法把它們加入到 ServiceManager 的 svclist 裡,藉此完成 ServiceManager 對服務的管理。

SystemServer 的 main 函式

native public static void init1(String[] args);
public static void main(String[] args) {
    if (SamplingProfilerIntegration.isEnabled()) {
        SamplingProfilerIntegration.start();
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                SamplingProfilerIntegration.writeSnapshot("system_server");
            }
        }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
    }
    // The system server has to run all of the time, so it needs to be
    // as efficient as possible with its memory usage.
    VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
    System.loadLibrary("android_servers"); // 載入本地函式庫 android_servers
    init1(args);
}

main 函式主要呼叫了本地方法 init1(args),其實作位於 base/services/jni/com_android_server_SystemService.cpp 中:

static void android_server_SystemServer_init1(JNIEnv* env, jobject clazz) {
    system_init();
}

system_init 中的服務循環框架

進一步觀察 system_init,可看到它啟動了閉合循環管理框架:

runtime->callStatic("com/android/server/SystemServer", "init2"); // 回調 SystemServer.java 的 init2 方法
if (proc->supportsProcesses()) {
    LOGI("System server: entering thread pool.\n");
    ProcessState::self()->startThreadPool();
    IPCThreadState::self()->joinThreadPool();
    LOGI("System server: exiting thread pool.\n");
}

init2 完成服務註冊

透過呼叫 SystemServer.java 中的 init2 方法來完成服務的註冊。init2 主要是建立了一個 ServerThread 執行緒,並啟動它以完成服務註冊:

public static final void init2() {
    Slog.i(TAG, "Entered the Android system server!");
    Thread thr = new ServerThread();
    thr.setName("android.server.ServerThread");
    thr.start();
}

真正負責註冊服務的邏輯則在 ServerThread 的 run 方法中:

try {
    Slog.i(TAG, "Entropy Service");
    ServiceManager.addService("entropy", new EntropyService());
    Slog.i(TAG, "Power Manager");
    power = new PowerManagerService();
    ServiceManager.addService(Context.POWER_SERVICE, power);
    Slog.i(TAG, "Activity Manager");
    context = ActivityManagerService.main(factoryTest);
    Slog.i(TAG, "Telephony Registry");
    ServiceManager.addService("telephony.registry", new TelephonyRegistry(context));
}

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved