BAT软件工程师带你深入理解AMS --- 一 AMS 的启动

一 Zygote fork

Zygote fork SystemServer 的过程如下:

ZygoteInit#forkSystemServer

ZygoteInit#handleSystemServerProcess

ZygoteInit#zygoteInit

RuntimeInit#applicationInit

RuntimeInit#findStaticMain

1.1 Zygote fork SystemServer 进程

ZygoteInit#forkSystemServer 配置system_server 的参数,uid gid 进程显示的名字等,然后调用native 的fork, 在子进程中调用handleSystemServerProcess

ZygoteInit.java

            ZygoteServer zygoteServer) {       
        /* Hardcoded command line to start the system server */
        String args[] = {            "--setuid=1000",            "--setgid=1000",            "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1023,1024,1032,1065,3001,3002,3003,3006,3007,3009,3010",            "--capabilities=" + capabilities + "," + capabilities,            "--nice-name=system_server",            "--runtime-args",            "--target-sdk-version=" + VMRuntime.SDK_VERSION_CUR_DEVELOPMENT,            "com.android.server.SystemServer",
        };        try {            /* Request to fork the system server process */
            pid = Zygote.forkSystemServer(
                    parsedArgs.uid, parsedArgs.gid,
                    parsedArgs.gids,
                    parsedArgs.runtimeFlags,                    null,
                    parsedArgs.permittedCapabilities,
                    parsedArgs.effectiveCapabilities);
        } catch (IllegalArgumentException ex) {            throw new RuntimeException(ex);
        }        /* For child process */
        if (pid == 0) {            if (hasSecondZygote(abiList)) {
                waitForSecondaryZygote(socketName);
            }

            zygoteServer.closeServerSocket();            return handleSystemServerProcess(parsedArgs);
        }        return null;
    }

1.2 System_service 进程启动,准备加载的ClassLoader

ZygoteInit.java    private static Runnable handleSystemServerProcess(ZygoteConnection.Arguments parsedArgs) {        // set umask to 0077 so new files and directories will default to owner-only permissions.
       
        if (parsedArgs.invokeWith != null) {

        } else {
            ClassLoader cl = null;            if (systemServerClasspath != null) {
                cl = createPathClassLoader(systemServerClasspath, parsedArgs.targetSdkVersion);

                Thread.currentThread().setContextClassLoader(cl);
            }            /*
             * Pass the remaining arguments to SystemServer.
             */
            return ZygoteInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl);
        }        /* should never reach here */
    }

1.3 RuntimeInit 初始化,进一步的准备初始化的环境

ZygoteInit.java    public static final Runnable zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader) {

        RuntimeInit.commonInit();
        ZygoteInit.nativeZygoteInit();        return RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader);
    }
1.4 通过findStaticMain 方法反射调用System_Server 的main 方法。
RuntimeInit.java    protected static Runnable applicationInit(int targetSdkVersion, String[] argv,
            ClassLoader classLoader) {      
        // Remaining arguments are passed to the start class's static main
        return findStaticMain(args.startClass, args.startArgs, classLoader);
    }

二 SystemServer进程

2.1 SystemServer 启动,然后运行 run 方法。
SystemServer.java public static void main(String[] args) { new SystemServer().run();
} public SystemServer() { // Check for factory test mode.
mFactoryTestMode = FactoryTest.getMode(); // Remember if it's runtime restart(when sys.boot_completed is already set) or reboot
mRuntimeRestart = "1".equals(SystemProperties.get("sys.boot_completed"));

    mRuntimeStartElapsedTime = SystemClock.elapsedRealtime();
    mRuntimeStartUptime = SystemClock.uptimeMillis();
}

2.2 System_Server 的run 方法
开始首先配置 VM 参数

Binder 参数,

Loop.prepareMainLooper,

创建系统Context createSystemContext

启动系统的各种服务,包括AMS。startBootstrapServices() startCoreServices() startOtherServices()

Looper.Loop();

private void run() {        try {
            ......            
            // the property. http://b/11463182
            SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());            // Mmmmmm... more memory!
            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.
            VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);

            ...... 
            // Ensure binder calls into the system always run at foreground priority.
            BinderInternal.disableBackgroundScheduling(true);            // Increase the number of binder threads in system_server
            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();
            Looper.getMainLooper().setSlowLogThresholdMs(
                    SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);            // Initialize native services.
            System.loadLibrary("android_servers");            // Initialize the system context.
            createSystemContext();

        } finally {
        }        // Start services.
        try {
            traceBeginAndSlog("StartServices");
            startBootstrapServices();
            startCoreServices();
            startOtherServices();
            SystemServerInitThreadPool.shutdown();
        } catch (Throwable ex) {

        } finally {
            traceEnd();
        }

        StrictMode.initVmDefaults(null);       
        // Loop forever.
        Looper.loop();        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

三 AMS 运行

SystemServer#startBootstrapServices 通过mSystemServiceManager 启动ActivityManagerService。

启动ActivityManagerService

3.1 mSystemServiceManager.startService
private void startBootstrapServices() {       
        // Activity manager runs the show.
        mActivityManagerService = mSystemServiceManager.startService(
                ActivityManagerService.Lifecycle.class).getService();
        mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
       
        mActivityManagerService.setSystemProcess();

3.2 启动ActivityManagerService
ActivityManagerService 准备工作线程,
准备Android 四大组件相关的数据结构,

public ActivityManagerService(Context systemContext) 
        mContext = systemCotex

        mSystemThread = ActivityThread.currentActivityThread();
        mUiContext = mSystemThread.getSystemUiContext();

        mHandlerThread = new ServiceThread(TAG,
                THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
        mHandlerThread.start();
        mHandler = new MainHandler(mHandlerThread.getLooper());
        mUiHandler = mInjector.getUiHandler(this);


        mFgBroadcastQueue = new BroadcastQueue(this, mHandler,                "foreground", BROADCAST_FG_TIMEOUT, false);
        mBgBroadcastQueue = new BroadcastQueue(this, mHandle                "background", BROADCAST_BG_TIMEOUT, true);
        mBroadcastQueues[0] = mFgBroadcastQueue;
        mBroadcastQueues[1] = mBgBroadcastQueue;
        
        mServices = new ActiveServices(this);
        mProviderMap = new ProviderMap(this);
    
        mStackSupervisor = createStackSupervisor();
        mActivityStarter = new ActivityStarter(this, mStackSupervisor);
        mRecentTasks = new RecentTasks(this, mStackSupervisor);
    }

3.3 AMS setSystemProcess()

AMS 通过 setSystemProcess 把System_Server 进程加入到AMS 的进程管理中。加载 framework-res.apk

public void setSystemProcess() {        try {
            ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
                    DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
            ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
            ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false,
                    DUMP_FLAG_PRIORITY_HIGH);
            ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
            ServiceManager.addService("dbinfo", new DbBinder(this));
            ServiceManager.addService("permission", new PermissionController(this));
            ServiceManager.addService("processinfo", new ProcessInfoService(this));

            ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(                    "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
            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);                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);
        }
    }

3.4 installSystemProviders

在中startOtherServices 安装 SettingProvider

mActivityManagerService.installSystemProviders();
3.5 setWindowManager
mActivityManagerService.setWindowManager(wm);
3.6 systemReady

各种服务启动完毕后,systemReady. 在systemReady 中先启动SystemUI, 然后启动Launcher.
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,539评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,594评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,871评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,963评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,984评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,763评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,468评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,357评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,850评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,002评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,144评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,823评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,483评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,026评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,150评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,415评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,092评论 2 355

推荐阅读更多精彩内容