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

Android 4.2.2 原始碼分析:AccountManagerService 是如何被啟動與註冊的

編輯:關於 Android 程式設計

本文以 Android 4.2.2 為基礎,追蹤 AccountManagerService 這個系統服務從「電源按下」到「註冊進 ServiceManager」的完整生命起點,藉此理解 Android 系統服務的註冊套路。

從 init 到 Zygote

Android 開機時,init 進程是第一個被啟動的,接著由它拉起 Zygote 進程。Zygote 執行的是 /system/bin/app_process,而 app_process 在執行過程中透過 AppRuntime::start() 建立虛擬機實例並註冊 JNI 方法:

int main(int argc, const char* const argv[])
{
    ...
    if (zygote) {
        runtime.start("com.android.internal.os.ZygoteInit",
                startSystemServer ? "start-system-server" : "");
    }
    ...
}

AppRuntime::start() 的註解已把職責說明得很清楚:

/*
 * Start the Android runtime. This involves starting the virtual machine
 * and calling the "static void main(String[] args)" method in the class
 * named by "className".
 *
 * Passes the main function two arguments, the class name and the specified
 * options string.
 */
void AndroidRuntime::start(const char* className, const char* options)
{
    ...
}

也就是說,這個函數做兩件事:啟動虛擬機,然後執行 className 所指名的 Java 類別的 main() 方法。傳入的 className 是 com.android.internal.os.ZygoteInit,於是我們看它的 main():

public static void main(String argv[]) {
    ...
    try {
        if (argv[1].equals("start-system-server")) {
            startSystemServer();
            ...
        }
    }
}

fork 出 SystemServer 進程

private static boolean startSystemServer()
        throws MethodAndArgsCaller, RuntimeException {
    ...
    int pid;

    try {
        ...
        /* Request to fork the system server process */
        pid = Zygote.forkSystemServer(
                parsedArgs.uid, parsedArgs.gid,
                parsedArgs.gids,
                parsedArgs.debugFlags,
                null,
                parsedArgs.permittedCapabilities,
                parsedArgs.effectiveCapabilities);
    } catch (IllegalArgumentException ex) {
        throw new RuntimeException(ex);
    }

    /* For child process */
    if (pid == 0) {
        handleSystemServerProcess(parsedArgs);
    }

    return true;
}

這裡 Zygote 進程 fork 出 SystemServer 進程,並在 handleSystemServerProcess() 中對子進程做初始化處理,包括關閉從 Zygote 複製過來的 socket。

進入 SystemServer 的初始化

接著呼叫 RuntimeInit.zygoteInit() 完成其餘初始化工作,其中會進入 SystemServer.main()。main() 經過一連串步驟後,呼叫本地方法 init1() 來啟動 SurfaceFlinger、SensorService 這類關鍵服務;之後 init1() 會從 native 層回呼 Java 層的 SystemServer.init2(),用來啟動 Java 層的各項服務:

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 是 Thread 的子類,在這個執行緒裡會建立訊息迴圈,然後依序啟動系統各項服務並註冊到 ServiceManager。

主題:AccountManagerService 的建立與註冊

class ServerThread extends Thread {
    private static final String TAG = "SystemServer";
    ...

    @Override
    public void run() {
        ...

        Looper.prepare();
        ...

        AccountManagerService accountManager = null;
        ...
        // Critical services...
        try {
            ...
            // The AccountManager must come before the ContentService
            try {
                Slog.i(TAG, "Account Manager");
                accountManager = new AccountManagerService(context);
                ServiceManager.addService(Context.ACCOUNT_SERVICE, accountManager);
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting Account Manager", e);
            }
            ...
        }
    }
    ...
}

程式碼裡那行註解「The AccountManager must come before the ContentService」是個重要線索:服務的啟動順序並非隨意安排。AccountManager 必須早於 ContentService 啟動,因為後續許多服務與應用都仰賴帳號體系;而每個服務都用 try-catch 包住,是為了讓單一服務啟動失敗不至于让整个系統起不來。

小結

把這條鏈路串起來就是:init → Zygote → app_process → ZygoteInit.main() → startSystemServer() → forkSystemServer() → handleSystemServerProcess() → RuntimeInit.zygoteInit() → SystemServer.main() → init1()(native 服務)→ init2() → ServerThread.run() → new AccountManagerService() + ServiceManager.addService()。

理解了這套「在 ServerThread 中 new 出來再 addService」的固定模式,後續要研究其他系統服務(例如 ActivityManagerService、PackageManagerService)的啟動機制,或想自行新增一個自製系統服務,都能沿著同一條路徑找到入口。

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