欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

“无处不在” 的系统核心服务 —— ActivityManagerService 启动流程解析

程序员文章站 2022-04-16 21:40:53
本文基于 Android 9.0 , 代码仓库地址 : "android_9.0.0_r45" 系列文章目录: "Java 世界的盘古和女娲 —— Zygote" "Zygote 家的大儿子 —— SystemServer" "Android 世界中,谁喊醒了 Zygote ?" 文中相关源码链接: ......

本文基于 android 9.0 , 代码仓库地址 :

系列文章目录:

java 世界的盘古和女娲 —— zygote

zygote 家的大儿子 —— systemserver

android 世界中,谁喊醒了 zygote ?

文中相关源码链接:

systemserver.java

activitymanagerservice.java

之前介绍 systemserver 启动流程 的时候说到,systemserver 进程启动了一系列的系统服务,activitymanagerservice 是其中最核心的服务之一。它和四大组件的启动、切换、调度及应用进程的管理和调度息息相关,其重要性不言而喻。本文主要介绍其启动流程,它是在 systemservermain() 中启动的,整个启动流程经历了 startbootstrapservicesstartcoreservice()startotherservice()。下面就顺着源码来捋一捋 activitymanagerservice 的启动流程,下文中简称 ams

private void startbootstrapservices() {
    ...
    
    // 1. ams 初始化
    mactivitymanagerservice = msystemservicemanager.startservice(
            activitymanagerservice.lifecycle.class).getservice();
    // 设置 ams 的系统服务管理器
    mactivitymanagerservice.setsystemservicemanager(msystemservicemanager);
    // 设置 ams 的应用安装器
    mactivitymanagerservice.setinstaller(installer);
    ...
    mactivitymanagerservice.initpowermanagement();
    ...
    // 2. ams.setsystemprocess()
    mactivitymanagerservice.setsystemprocess();
    ...
}

private void startcoreservices{
    ...
    
    mactivitymanagerservice.setusagestatsmanager(
            localservices.getservice(usagestatsmanagerinternal.class));
    ...
}

private void startherservice{
    ...
    
    // 3. 安装系统 provider
    mactivitymanagerservice.installsystemproviders();
    ...
    final watchdog watchdog = watchdog.getinstance();
            watchdog.init(context, mactivitymanagerservice);
    ...
    mactivitymanagerservice.setwindowmanager(wm);
    ...
    networkpolicy = new networkpolicymanagerservice(context, mactivitymanagerservice,
                        networkmanagement);
    ...
    if (safemode) {
        tracebeginandslog("entersafemodeanddisablejitcompilation");
        mactivitymanagerservice.entersafemode();
        // disable the jit for the system_server process
        vmruntime.getruntime().disablejitcompilation();
        traceend();
    }
    ...
    mpowermanagerservice.systemready(mactivitymanagerservice.getappopsservice());
    ...
    // 4. ams.systemready()
    mactivitymanagerservice.systemready(() -> {
        ...
        mactivitymanagerservice.startobservingnativecrashes();
    }
}

ams 初始化

mactivitymanagerservice = msystemservicemanager.startservice(
                activitymanagerservice.lifecycle.class).getservice();

ams 通过 systemservicemanager.startservice() 方法初始化,startservice() 在之前的文章中已经分析过,其作用是根据参数传入的类通过反射进行实例化,并回调其 onstart() 方法。注意这里传入的是 activitymanagerservice.lifecycle.classlifecycle 是 ams 的一个静态内部类。

public static final class lifecycle extends systemservice {
    private final activitymanagerservice mservice;

    // 构造函数中新建 activitymanagerservice 对象
    public lifecycle(context context) {
        super(context);
        mservice = new activitymanagerservice(context);
    }

    @override
    public void onstart() {
        mservice.start();
    }

    @override
    public void onbootphase(int phase) {
        mservice.mbootphase = phase;
        if (phase == phase_system_services_ready) {
            mservice.mbatterystatsservice.systemservicesready();
            mservice.mservices.systemservicesready();
        }
    }

    @override
    public void oncleanupuser(int userid) {
        mservice.mbatterystatsservice.oncleanupuser(userid);
    }

    public activitymanagerservice getservice() {
        return mservice;
    }
}

lifecycle 的构造函数中初始化了 ams。再来看看 ams 的构造函数。

public activitymanagerservice(context systemcontext) {
    minjector = new injector();
    // ams 上下文
    mcontext = systemcontext;

    mfactorytest = factorytest.getmode();
    // activitythread 对象
    msystemthread = activitythread.currentactivitythread(); 
    // contextimpl 对象
    muicontext = msystemthread.getsystemuicontext(); 

    mpermissionreviewrequired = mcontext.getresources().getboolean(
            com.android.internal.r.bool.config_permissionreviewrequired);

    // 线程名为 activitymanager 的前台线程,servicethread 继承于 handlerthread
    mhandlerthread = new servicethread(tag,
            thread_priority_foreground, false /*allowio*/);
    mhandlerthread.start();
    // 获取 mhandlerthread 的 handler 对象
    mhandler = new mainhandler(mhandlerthread.getlooper());
    // 创建名为 android.ui 的线程
    muihandler = minjector.getuihandler(this);

    // 不知道什么作用
    mprocstarthandlerthread = new servicethread(tag + ":procstart",
            thread_priority_foreground, false /* allowio */);
    mprocstarthandlerthread.start();
    mprocstarthandler = new handler(mprocstarthandlerthread.getlooper());

    mconstants = new activitymanagerconstants(this, mhandler);

    /* static; one-time init here */
    // 根据优先级 kill 后台应用进程
    if (skillhandler == null) {
        skillthread = new servicethread(tag + ":kill",
                thread_priority_background, true /* allowio */);
        skillthread.start();
        skillhandler = new killhandler(skillthread.getlooper());
    }

    // 前台广播队列,超时时间为 10 秒
    mfgbroadcastqueue = new broadcastqueue(this, mhandler,
            "foreground", broadcast_fg_timeout, false);
    // 后台广播队列,超时时间为 60 秒
    mbgbroadcastqueue = new broadcastqueue(this, mhandler,
            "background", broadcast_bg_timeout, true);
    mbroadcastqueues[0] = mfgbroadcastqueue;
    mbroadcastqueues[1] = mbgbroadcastqueue;

    // 创建 activeservices
    mservices = new activeservices(this);
    mprovidermap = new providermap(this);
    // 创建 apperrors,用于处理应用中的错误
    mapperrors = new apperrors(muicontext, this);

    // 创建 /data/system 目录
    file datadir = environment.getdatadirectory();
    file systemdir = new file(datadir, "system");
    systemdir.mkdirs();

    mappwarnings = new appwarnings(this, muicontext, mhandler, muihandler, systemdir);

    // todo: move creation of battery stats service outside of activity manager service.
    // 创建 batterystatsservice,其信息保存在 /data/system/procstats 中
    // 这里有个 todo,打算把 batterystatsservice 的创建移除 ams
    mbatterystatsservice = new batterystatsservice(systemcontext, systemdir, mhandler);
    mbatterystatsservice.getactivestatistics().readlocked();
    mbatterystatsservice.schedulewritetodisk();
    monbattery = debug_power ? true
            : mbatterystatsservice.getactivestatistics().getisonbattery();
    mbatterystatsservice.getactivestatistics().setcallback(this);

    // 创建 processstatsservice,并将其信息保存在 /data/system/procstats 中
    mprocessstats = new processstatsservice(this, new file(systemdir, "procstats"));

    mappopsservice = minjector.getappopsservice(new file(systemdir, "appops.xml"), mhandler);

    // 定义 contentprovider 访问指定 uri 数据的权限
    mgrantfile = new atomicfile(new file(systemdir, "urigrants.xml"), "uri-grants");

    // 多用户管理
    musercontroller = new usercontroller(this);

    mvrcontroller = new vrcontroller(this);

    // 获取 opengl 版本
    gl_es_version = systemproperties.getint("ro.opengles.version",
        configurationinfo.gl_es_version_undefined);

    if (systemproperties.getint("sys.use_fifo_ui", 0) != 0) {
        musefifouischeduling = true;
    }

    mtrackingassociations = "1".equals(systemproperties.get("debug.track-associations"));
    mtempconfig.settodefaults();
    mtempconfig.setlocales(localelist.getdefault());
    mconfigurationseq = mtempconfig.seq = 1;
    // 创建 activitystacksupervisor ,用于管理 activity 任务栈
    mstacksupervisor = createstacksupervisor();
    mstacksupervisor.onconfigurationchanged(mtempconfig);
    mkeyguardcontroller = mstacksupervisor.getkeyguardcontroller();
    mcompatmodepackages = new compatmodepackages(this, systemdir, mhandler);
    mintentfirewall = new intentfirewall(new intentfirewallinterface(), mhandler);
    mtaskchangenotificationcontroller =
            new taskchangenotificationcontroller(this, mstacksupervisor, mhandler);
    // 创建 activitystartcontroller 对象,用于管理 activity 的启动
    mactivitystartcontroller = new activitystartcontroller(this);
    // 创建最近任务栈 recenttask 对象
    mrecenttasks = createrecenttasks();
    mstacksupervisor.setrecenttasks(mrecenttasks);
    mlocktaskcontroller = new locktaskcontroller(mcontext, mstacksupervisor, mhandler);
    mlifecyclemanager = new clientlifecyclemanager();

    // 创建 cputracker 线程,追踪 cpu 状态
    mprocesscputhread = new thread("cputracker") {
        @override
        public void run() {
            synchronized (mprocesscputracker) {
                mprocesscpuinitlatch.countdown();
                mprocesscputracker.init(); // 初始化 processcputracker。注意同步问题
            }
            while (true) {
                try {
                    try {
                        synchronized(this) {
                            final long now = systemclock.uptimemillis();
                            long nextcpudelay = (mlastcputime.get()+monitor_cpu_max_time)-now;
                            long nextwritedelay = (mlastwritetime+battery_stats_time)-now;
                            //slog.i(tag, "cpu delay=" + nextcpudelay
                            //        + ", write delay=" + nextwritedelay);
                            if (nextwritedelay < nextcpudelay) {
                                nextcpudelay = nextwritedelay;
                            }
                            if (nextcpudelay > 0) {
                                mprocesscpumutexfree.set(true);
                                this.wait(nextcpudelay);
                            }
                        }
                    } catch (interruptedexception e) {
                    }
                    // 更新 cpu 统计信息
                    updatecpustatsnow();
                } catch (exception e) {
                    slog.e(tag, "unexpected exception collecting process stats", e);
                }
            }
        }
    };

    // hidden api 设置
    mhiddenapiblacklist = new hiddenapisettings(mhandler, mcontext);

    // 设置 watchdog 监控
    watchdog.getinstance().addmonitor(this);
    watchdog.getinstance().addthread(mhandler);

    // bind background thread to little cores
    // this is expected to fail inside of framework tests because apps can't touch cpusets directly
    // make sure we've already adjusted system_server's internal view of itself first
    // 更新进程的 oom_adj 值
    updateoomadjlocked();
    try {
        process.setthreadgroupandcpuset(backgroundthread.get().getthreadid(),
                process.thread_group_bg_noninteractive);
    } catch (exception e) {
        slog.w(tag, "setting background thread cpuset failed");
    }
}

ams 的构造函数中做了很多事情,代码中作了很多注释,这里就不再展开细说了。

lifecycle 的构造函数中初始化了 ams,然后会调用 lifecycle.onstart(),最终调用的是 ams.start() 方法。

    private void start() {
    // 移除所有进程组
    removeallprocessgroups();
    // 启动构造函数中创建的 cputracker 线程,监控 cpu 使用情况
    mprocesscputhread.start();

    // 启动 batterystatsservice,统计电池信息
    mbatterystatsservice.publish();
    mappopsservice.publish(mcontext);
    // 启动 localservice ,将 activitymanagerinternal 加入服务列表
    localservices.addservice(activitymanagerinternal.class, new localservice());
    // 等待 mprocesscputhread 线程中的同步代码块执行完毕。
    // 在执行 mprocesscputracker.init() 方法时访问 mprocesscputracker 将阻塞
    try {
        mprocesscpuinitlatch.await();
    } catch (interruptedexception e) {
        thread.currentthread().interrupt();
        throw new illegalstateexception("interrupted wait during start");
    }
}

ams 的初始化工作到这里就基本结束了,我们再回到 startbootstrapservices() 中,看看 ams 的下一步动作 setsystemprocess()

ams.setsystemprocess()

public void setsystemprocess() {
    try {
        // 注册各种服务
        // 注册 ams
        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);
        // 注册 graphicsbinder
        servicemanager.addservice("gfxinfo", new graphicsbinder(this));
        // 注册 dbbinder
        servicemanager.addservice("dbinfo", new dbbinder(this));
        if (monitor_cpu_usage) {
            // 注册 dbbinder
            servicemanager.addservice("cpuinfo", new cpubinder(this),
                    /* allowisolated= */ false, dump_flag_priority_critical);
        }
        // 注册权限管理者 permissioncontroller
        servicemanager.addservice("permission", new permissioncontroller(this
        // 注册进程信息服务 processinfoservice
        servicemanager.addservice("processinfo", new processinfoservice(this));

        // 获取包名为 android 的应用信息,framework-res.apk
        applicationinfo info = mcontext.getpackagemanager().getapplicationinfo(
                "android", stock_pm_flags | match_system_only);
        msystemthread.installsystemapplicationinfo(info, getclass().getclassloader());

        synchronized (this) {
            // 创建 processrecord
            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);
            }
            // 更新 mlruprocesses
            updatelruprocesslocked(app, false, null);
            // 更新进程对应的 oom_adj 值
            updateoomadjlocked();
        }
    } catch (packagemanager.namenotfoundexception e) {
        throw new runtimeexception(
                "unable to find android system package", e);
    }

    // start watching app ops after we and the package manager are up and running.
    // 当 packager manager 启动并运行时开始监听 app ops
    mappopsservice.startwatchingmode(appopsmanager.op_run_in_background, null,
            new iappopscallback.stub() {
                @override public void opchanged(int op, int uid, string packagename) {
                    if (op == appopsmanager.op_run_in_background && packagename != null) {
                        if (mappopsservice.checkoperation(op, uid, packagename)
                                != appopsmanager.mode_allowed) {
                            runinbackgrounddisabled(uid);
                        }
                    }
                }
            });
}

setsystemprocess() 的主要工作就是向 servicemanager 注册关联的系统服务。

ams.installsystemproviders()

public final void installsystemproviders() {
        list<providerinfo> providers;
        synchronized (this) {
            processrecord app = mprocessnames.get("system", system_uid);
            providers = generateapplicationproviderslocked(app);
            if (providers != null) {
                for (int i=providers.size()-1; i>=0; i--) {
                    providerinfo pi = (providerinfo)providers.get(i);
                    if ((pi.applicationinfo.flags&applicationinfo.flag_system) == 0) {
                        slog.w(tag, "not installing system proc provider " + pi.name
                                + ": not system .apk");
                        // 移除非系统 provier
                        providers.remove(i); 
                    }
                }
            }
        }

        // 安装系统 provider
        if (providers != null) {
            msystemthread.installsystemproviders(providers);
        }

        synchronized (this) {
            msystemprovidersinstalled = true;
        }

        mconstants.start(mcontext.getcontentresolver());
        // 创建 coresettingsobserver ,监控核心设置的变化
        mcoresettingsobserver = new coresettingsobserver(this);
        // 创建 fontscalesettingobserver,监控字体的变化
        mfontscalesettingobserver = new fontscalesettingobserver();
        // 创建 developmentsettingsobserver
        mdevelopmentsettingsobserver = new developmentsettingsobserver();
        globalsettingstopropertiesmapper.start(mcontext.getcontentresolver());

        // now that the settings provider is published we can consider sending
        // in a rescue party.
        rescueparty.onsettingsproviderpublished(mcontext);

        //musagestatsservice.monitorpackages();
    }

installsystemproviders() 的主要工作是安装系统 proviers。

ams.systemready()

ams.systemready() 是 ams 启动流程的最后一步了。

public void systemready(final runnable goingcallback, timingstracelog tracelog) {
    ...
    synchronized(this) {
        if (msystemready) { // 首次调用 msystemready 为 false
            // if we're done calling all the receivers, run the next "boot phase" passed in
            // by the systemserver
            if (goingcallback != null) {
                goingcallback.run();
            }
            return;
        }

        // 一系列 systemready()
        mhasheavyweightfeature = mcontext.getpackagemanager().hassystemfeature(
                packagemanager.feature_cant_save_state);
        mlocaldeviceidlecontroller
                = localservices.getservice(deviceidlecontroller.localservice.class);
        massistutils = new assistutils(mcontext);
        mvrcontroller.onsystemready();
        // make sure we have the current profile info, since it is needed for security checks.
        musercontroller.onsystemready();
        mrecenttasks.onsystemreadylocked();
        mappopsservice.systemready();
        msystemready = true;
    }

    ...
    
    arraylist<processrecord> procstokill = null;
    synchronized(mpidsselflocked) {
        for (int i=mpidsselflocked.size()-1; i>=0; i--) {
            processrecord proc = mpidsselflocked.valueat(i);
            if (!isallowedwhilebooting(proc.info)){
                if (procstokill == null) {
                    procstokill = new arraylist<processrecord>();
                }
                procstokill.add(proc);
            }
        }
    }

    synchronized(this) {
        if (procstokill != null) {
            for (int i=procstokill.size()-1; i>=0; i--) {
                processrecord proc = procstokill.get(i);
                removeprocesslocked(proc, true, false, "system update done");
            }
        }

        // now that we have cleaned up any update processes, we
        // are ready to start launching real processes and know that
        // we won't trample on them any more.
        mprocessesready = true;
    }

    ...

    if (goingcallback != null) goingcallback.run();
    mbatterystatsservice.noteevent(batterystats.historyitem.event_user_running_start,
            integer.tostring(currentuserid), currentuserid);
    mbatterystatsservice.noteevent(batterystats.historyitem.event_user_foreground_start,
            integer.tostring(currentuserid), currentuserid);
    // 回调所有 systemservice 的 onstartuser() 方法
    msystemservicemanager.startuser(currentuserid);

    synchronized (this) {
        // only start up encryption-aware persistent apps; once user is
        // unlocked we'll come back around and start unaware apps
        startpersistentapps(packagemanager.match_direct_boot_aware);

        // start up initial activity.
        mbooting = true;
        // enable home activity for system user, so that the system can always boot. we don't
        // do this when the system user is not setup since the setup wizard should be the one
        // to handle home activity in this case.
        if (usermanager.issplitsystemuser() &&
                settings.secure.getint(mcontext.getcontentresolver(),
                     settings.secure.user_setup_complete, 0) != 0) {
            componentname cname = new componentname(mcontext, systemuserhomeactivity.class);
            try {
                appglobals.getpackagemanager().setcomponentenabledsetting(cname,
                        packagemanager.component_enabled_state_enabled, 0,
                        userhandle.user_system);
            } catch (remoteexception e) {
                throw e.rethrowasruntimeexception();
            }
        }

        // 启动桌面 home 应用
        starthomeactivitylocked(currentuserid, "systemready");

       ...

        long ident = binder.clearcallingidentity();
        try {
            // 发送广播 user_started
            intent intent = new intent(intent.action_user_started);
            intent.addflags(intent.flag_receiver_registered_only
                    | intent.flag_receiver_foreground);
            intent.putextra(intent.extra_user_handle, currentuserid);
            broadcastintentlocked(null, null, intent,
                    null, null, 0, null, null, null, op_none,
                    null, false, false, my_pid, system_uid,
                    currentuserid);
            // 发送广播 user_starting
            intent = new intent(intent.action_user_starting);
            intent.addflags(intent.flag_receiver_registered_only);
            intent.putextra(intent.extra_user_handle, currentuserid);
            broadcastintentlocked(null, null, intent,
                    null, new iintentreceiver.stub() {
                        @override
                        public void performreceive(intent intent, int resultcode, string data,
                                bundle extras, boolean ordered, boolean sticky, int sendinguser)
                                throws remoteexception {
                        }
                    }, 0, null, null,
                    new string[] {interact_across_users}, op_none,
                    null, true, false, my_pid, system_uid, userhandle.user_all);
        } catch (throwable t) {
            slog.wtf(tag, "failed sending first user broadcasts", t);
        } finally {
            binder.restorecallingidentity(ident);
        }
        mstacksupervisor.resumefocusedstacktopactivitylocked();
        musercontroller.senduserswitchbroadcasts(-1, currentuserid);

        binderinternal.nsetbinderproxycountwatermarks(6000,5500);
        binderinternal.nsetbinderproxycountenabled(true);
        binderinternal.setbinderproxycountcallback(
            new binderinternal.binderproxylimitlistener() {
                @override
                public void onlimitreached(int uid) {
                    if (uid == process.system_uid) {
                        slog.i(tag, "skipping kill (uid is system)");
                    } else {
                        killuid(userhandle.getappid(uid), userhandle.getuserid(uid),
                                "too many binders sent to system");
                    }
                }
            }, mhandler);
    }
}

systemready() 方法源码很长,上面做了很多删减。注意其中的 starthomeactivitylocked() 方法会启动桌面 activity 。

boolean starthomeactivitylocked(int userid, string reason) {
    ...
    intent intent = gethomeintent();
    activityinfo ainfo = resolveactivityinfo(intent, stock_pm_flags, userid);
    if (ainfo != null) {
        intent.setcomponent(new componentname(ainfo.applicationinfo.packagename, ainfo.name));
        // don't do this if the home app is currently being
        // instrumented.
        ainfo = new activityinfo(ainfo);
        ainfo.applicationinfo = getappinfoforuser(ainfo.applicationinfo, userid);
        processrecord app = getprocessrecordlocked(ainfo.processname,
                ainfo.applicationinfo.uid, true);
        if (app == null || app.instr == null) {
            intent.setflags(intent.getflags() | flag_activity_new_task);
            final int resolveduserid = userhandle.getuserid(ainfo.applicationinfo.uid);
            // for anr debugging to verify if the user activity is the one that actually
            // launched.
            final string myreason = reason + ":" + userid + ":" + resolveduserid;
            // 启动桌面 activity
            mactivitystartcontroller.starthomeactivity(intent, ainfo, myreason);
        }
    } else {
        slog.wtf(tag, "no home screen found for " + intent, new throwable());
    }

    return true;
}

activitystartcontroller 负责启动 activity,至此,桌面应用就启动了。

最后

整篇写下来感觉就像小学生流水日记一样,但是读源码,就像有钱人的生活一样,往往是那么朴实无华,且枯燥。我不经意间看了看我的劳力士,太晚了,时序图后面再补上吧!

最后,下集预告,接着这篇,activity 的启动流程分析,敬请期待!

文章首发微信公众号: 秉心说 , 专注 java 、 android 原创知识分享,leetcode 题解。

更多最新原创文章,扫码关注我吧!

“无处不在” 的系统核心服务 —— ActivityManagerService 启动流程解析