ActivityManagerService笔记

2024-05-15  本文已影响0人  R7_Perfect

1.AMS 概述

AMS 是系统的引导服务,应用进程的启动、切换和调度、四大组件的启动和管
理都需要 AMS 的支持。从这里可以看出 AMS 的功能会十分的繁多,当然它并不
是一个类承担这个重责,它有一些关联类,这在文章后面会讲到。AMS 的涉及
的知识点非常多,这篇文章主要会讲解 AMS 的以下几个知识点:

2.AMS 的启动流程

整理了一下启动流程:
开机启动:


2018030813463528.png

SyetemServer在启动时做了如下工作:

  1. 启动Binder线程池,这样就可以与其他进程进行通信。
  2. 创建SystemServiceManager用于对系统的服务进行创建、启动和生命周期管理。
  3. 启动各种系统服务。
AMS启动.png

ActivityManagerService的构造函数

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);

    // 根据优先级 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");
    }
}

最终调用ActivityManagerService中的start方法

 private void start() {
    removeAllProcessGroups();   // 移除所有进程组
    mProcessCpuThread.start();//启动同步CPU的线程,监控 cpu 使用情况
    mBatteryStatsService.publish();//订阅WIFI和mobile电量,统计电池信息
    mAppOpsService.publish(mContext);//订阅app管理服务(前后台等)
    Slog.d("AppOps", "AppOpsService published");
    LocalServices.addService(ActivityManagerInternal.class, new LocalService());//启动本地服务
    mActivityTaskManager.onActivityManagerInternalAdded();//启动ActivityManagerInternal,UriGrantsManagerInternal
    mUgmInternal.onActivityManagerInternalAdded();//UriGrantsManagerService启动本地服务
    mPendingIntentController.onActivityManagerInternalAdded();//pending intent controller启动本地服务
// 等待 mProcessCpuThread 线程中的同步代码块执行完毕。
    try {
        mProcessCpuInitLatch.await();
    } catch (InterruptedException e) {
        Slog.wtf(TAG, "Interrupted wait during start", e);
        Thread.currentThread().interrupt();
        throw new IllegalStateException("Interrupted wait during start");
    }
}

相关代码与方法:
SystemServer
ActivityManagerService
SystemServiceManager

3.AMS 与进程启动

Zygote 的 Java 框架层中,会创建一个 Server 端的 Socket,这个 Socket 用来等待
AMS 来请求 Zygote 来创建新的应用程序进程。要启动一个应用程序,首先要保
证这个应用程序所需要的应用程序进程已经被启动。AMS 在启动应用程序时会
检查这个应用程序需要的应用程序进程是否存在,不存在就会请求 Zygote 进程
将需要的应用程序进程启动。Service 的启动过程中会调用 ActiveServices 的
bringUpServiceLocked 方法,

 private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg, boolean whileRestarting, boolean permissionsReviewRequired) throws TransactionTooLargeException {
    ...
    final String procName = r.processName;//1
    ...
    ProcessRecord app;
    if (!isolated) {
        app = mAm.getProcessRecordLocked(procName, r.appInfo.uid, false);//2
        ...
        if (app != null && app.thread != null) {//3
            try {
                app.addPackage(r.appInfo.packageName, r.appInfo.longVersionCode, mAm.mProcessStats);
                realStartServiceLocked(r, app, execInFg);//4
                return null;
            }...
        }
    } else {
       ...
    }
    if (app == null && !permissionsReviewRequired) {//5
        if ((app=mAm.startProcessLocked(procName, r.appInfo, true, intentFlags,
                hostingRecord, false, isolated, false)) == null) {//6
           ...
        }
        if (isolated) {
            r.isolatedProc = app;
        }
    }
    ...
}

代码:ActiveServices
在注释 1 处得到 ServiceRecord 的 processName 的值赋值给 procName ,其中
ServiceRecord 用来描述 Service 的 android:process 属性。
注释 2 处将 procName和 Service 的 uid 传入到 AMS 的 getProcessRecordLocked 方法中,来查询是否存在一个与 Service 对应的 ProcessRecord 类型的对象 app,ProcessRecord 主要用来记录运行的应用程序进程的信息。
注释 5 处判断 Service 对应的 app 为 null 则说明用来运行 Service 的应用程序进程不存在,则调用注释 6 处的 AMS 的startProcessLocked 方法来创建对应的应用程序进程,

4.AMS 主要类

其他

补充下SystemServer启动的服务:


1715843623236.png
上一篇下一篇

猜你喜欢

热点阅读