Android系統從加電到Home桌面出現流程分析(基於Android-2.3)

android啟動

當引導程序啟動Linux內核後,會加載各種驅動和數據結構,當有瞭驅動以後,開始啟動Android系統同時會加載用戶級別的第一個進程init(system\core\init.c)代碼如下:

int main(int argc, char **argv)
{

    // 創建文件夾 掛載
    mount("tmpfs", "/dev", "tmpfs", 0, "mode=0755");
    mkdir("/dev/pts", 0755);

    // 打卡日志
    log_init();

    INFO("reading config file\n");
    // 加載init.rc配置文件
    init_parse_config_file("/init.rc");

} 

加載init.rc文件,會啟動一個Zygote進程,此進程是Android系統的一個母進程,用來啟動Android的其他服務進程,代碼:

service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server
socket zygote stream 666
onrestart write /sys/android_power/request_state wake
onrestart write /sys/power/state on
onrestart restart media
onrestart restart netd

從c++代碼跳轉到java代碼:

int main(int argc, const char* const argv[])
{
    ...
    // Android運行時環境
    AppRuntime runtime;
    ...
    // Next arg is startup classname or "--zygote"
    if (i < argc) {
        arg = argv[i++];
        if (0 == strcmp("--zygote", arg)) {
            bool startSystemServer = (i < argc) ? 
                    strcmp(argv[i], "--start-system-server") == 0 : false;
            setArgv0(argv0, "zygote");
            set_process_name("zygote");
            // 啟動java代碼
            runtime.start("com.android.internal.os.ZygoteInit",
         ...

}

ZygoteInit.java 代碼:

public static void main(String argv[]) {
    try {
        VMRuntime.getRuntime().setMinimumHeapSize(5 * 1024 * 1024);

        // 加載Android依賴的類
        preloadClasses();
        //cacheRegisterMaps();
        preloadResources();
        ...

        if (argv[1].equals("true")) {
            // 啟動系統服務
            startSystemServer();
        } else if (!argv[1].equals("false")) {
       ...
}


private static boolean startSystemServer()
     ...
        args = new String[] {
            "--setuid=1000",
            "--setgid=1000",
            "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,3001,3002,3003,3006",
            "--capabilities=130104352,130104352",
            "--rlimit=8,",
            "--runtime-init",
            "--nice-name=system_server",
            "com.android.server.SystemServer",
      ...

        /* Request to fork the system server process */
        // 母進程開始分叉服務 啟動SystemServer
        pid = Zygote.forkSystemServer(
                parsedArgs.uid, parsedArgs.gid,
                parsedArgs.gids, debugFlags, rlimits,
                parsedArgs.permittedCapabilities,
                parsedArgs.effectiveCapabilities);
    ..
}

SystemServer.java 代碼

public static void main(String[] args) {
    ... 
    // 加載jni庫
    System.loadLibrary("android_servers");
    // 調用native方法
    init1(args);
}
native public static void init1(String[] args);

SystemServer 對應的c++代碼 com_android_server_SystemServer.cpp 代碼如下:

// 類似java的抽象方法
extern "C" int system_init();

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

/*
 * JNI registration.
 */
static JNINativeMethod gMethods[] = {
    /* name, signature, funcPtr */ 
    // 函數指針 把init1方法映射到android_server_SystemServer_init1
    { "init1", "([Ljava/lang/String;)V", (void*) android_server_SystemServer_init1 },
};

system_init 的實現方法在System_init.cpp 代碼如下:

extern "C" status_t system_init()
{
    ...
    // 啟動硬件的服務
    if (strcmp(propBuf, "1") == 0) {
        // Start the SurfaceFlinger
        SurfaceFlinger::instantiate();
    }



    AndroidRuntime* runtime = AndroidRuntime::getRuntime();

    LOGI("System server: starting Android services.\n");
    // 啟動完硬件服務後,又回到Systemserver的init2方法
    runtime->callStatic("com/android/server/SystemServer", "init2");
    ...
}

SystemServer 的init2方法代碼:

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方法:

public void run() {

// 開啟Android各種服務並且添加到ServiceManager去管理
Slog.i(TAG, “Device Policy”);
devicePolicy = new DevicePolicyManagerService(context);
ServiceManager.addService(Context.DEVICE_POLICY_SERVICE, ottle =

    ...
    // We now tell the activity manager it is okay to run third party
    // code.  It will call back into us once it has gotten to the state
    // where third party code can really run (but before it has actually
    // started launching the initial applications), for us to complete our
    // initialization.
    // 各種服務開啟後調用ActivityManagerService.systemReady
    ((ActivityManagerService)ActivityManagerNative.getDefault())
            .systemReady(new Runnable() {
        public void run() {
            Slog.i(TAG, "Making services ready");

ActivityMangerService的systemReady的方法:

public void systemReady(final Runnable goingCallback) {
        ...
        // 打開第一個Activity
            mMainStack.resumeTopActivityLocked(null);
        }
    }

ActivityStack的resumeTopActivityLocked方法

final boolean resumeTopActivityLocked(ActivityRecord prev) {
        // Find the first activity that is not finishing.
        // 沒有已經打開的Activity next為 null
        ActivityRecord next = topRunningActivityLocked(null);

        // Remember how we'll process this pause/resume situation, and ensure
        // that the state is reset however we wind up proceeding.
        final boolean userLeaving = mUserLeaving;
        mUserLeaving = false;

        if (next == null) {
            // There are no more activities!  Let's just start up the
            // Launcher...

            if (mMainStack) {
                // 啟動lucher應用的鎖屏界面
                return mService.startHomeActivityLocked();
            }
        }

Android系統啟動完成,打開瞭Luncher應用的Home界面。

You May Also Like