AMS 通过 SystemServiceManager 来启动

public final class SystemServer implements Dumpable {

    public static void main(String[] args) {
        new SystemServer().run();
    }

    private void run() {
        ... 省略部分

        try {
            t.traceBegin("StartServices");
            
            // AMS 是引导服务
            startBootstrapServices(t);    // 启动引导服务
            startCoreServices(t);        // 启动核心服务
            startOtherServices(t);        // 启动其他服务
            startApexServices(t);   // 启动Apex服务
        } /*省略 catch*/

        ... 省略部分

    }

    // 启动 AMS 的函数
    private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
        ... 省略部分

        // Activity manager runs the show.
        // 相当于创建了一个 ActivityTaskManagerService 类
        ActivityTaskManagerService atm = mSystemServiceManager.startService(
                ActivityTaskManagerService.Lifecycle.class).getService();
        
        // 分析 ActivityManagerService.Lifecycle.startService
        mActivityManagerService = ActivityManagerService
            .Lifecycle.startService(    // startService 会呼叫 onStart 方法
                mSystemServiceManager, 
                atm
        );
        
        ... 省略部分
        
        // 之后分析
        mActivityManagerService.setSystemProcess();

        ... 省略部分

    }

}

AMS 通过 AMS#Lifecycle 内部类创建

// ActivityManagerService.java

    // 继承于 SystemService (抽象类)
    public static final class Lifecycle extends SystemService {
        private final ActivityManagerService mService;
        private static ActivityTaskManagerService sAtm;

        public Lifecycle(Context context) {
            super(context);

            // 创建 AMS
            mService = new ActivityManagerService(context, sAtm);
        }
        
        
        // SystemService#startService 会呼叫到 onStart 方法
        @Override
        public void onStart() {
            // AMS 私有函数 start() 
            mService.start();
        }

        ... 省略部分
    }

SystemService#startService 调用 onStart 方法

// ActivityManagerService.java

    private void start() {
        // 启动电池统计服务
        mBatteryStatsService.publish();
        mAppOpsService.publish();
        Slog.d("AppOps", "AppOpsService published");
        
        // 添加到本地 LocalServices 中
        LocalServices.addService(ActivityManagerInternal.class, mInternal);
        LocalManagerRegistry.addManager(ActivityManagerLocal.class,
                (ActivityManagerLocal) mInternal);
        
        mActivityTaskManager.onActivityManagerInternalAdded();
        mPendingIntentController.onActivityManagerInternalAdded();
        mAppProfiler.onActivityManagerInternalAdded();
    }

构造函数

// /services/core/java/com/android/server/am/ActivityManagerService.java

// AMS 构建函数
public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
    
    LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
    mInjector = new Injector(systemContext);
    
    // 系统级 Context
    mContext = systemContext;
    
    
    mFactoryTest = FactoryTest.getMode();
    // 获取当前的 ActiivtyThread
    mSystemThread = ActivityThread.currentActivityThread();
    
    // 取得 系统 UiContext
    mUiContext = mSystemThread.getSystemUiContext();
    Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
    
    // 创建 Handler Thread 处理 Handler 消息
    mHandlerThread = new ServiceThread(TAG,
            THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
    mHandlerThread.start();
    mHandler = new MainHandler(mHandlerThread.getLooper());
    
    // 处理 UI 相关讯息的 Handler
    mUiHandler = mInjector.getUiHandler(this);
    mProcStartHandlerThread = new ServiceThread(TAG + ":procStart",
            THREAD_PRIORITY_FOREGROUND, false /* allowIo */);
    mProcStartHandlerThread.start();
    
    // 进程启动的 Handler
    mProcStartHandler = new Handler(mProcStartHandlerThread.getLooper());
    
    // 管理 AMS 的常量,厂商制定系统就有可能修改此处
    mConstants = new ActivityManagerConstants(mContext, this, mHandler);
    final ActiveUids activeUids = new ActiveUids(this, true /* postChangesToAtm */);
    mPlatformCompat = (PlatformCompat) ServiceManager.getService(
            Context.PLATFORM_COMPAT_SERVICE);
    mProcessList = mInjector.getProcessList(this);
    mProcessList.init(this, activeUids, mPlatformCompat);
    mAppProfiler = new AppProfiler(this, BackgroundThread.getHandler().getLooper(),
            new LowMemDetector(this));
    mPhantomProcessList = new PhantomProcessList(this);
    mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids);
    
    
    // Broadcast policy parameters
    // 初始化前、后台、卸载广播队列
    // 系统会优先便利发送前台广播
    final BroadcastConstants foreConstants = new BroadcastConstants(
            Settings.Global.BROADCAST_FG_CONSTANTS); // 前台
    foreConstants.TIMEOUT = BROADCAST_FG_TIMEOUT;
    final BroadcastConstants backConstants = new BroadcastConstants(
            Settings.Global.BROADCAST_BG_CONSTANTS); // 后台
    backConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
    final BroadcastConstants offloadConstants = new BroadcastConstants(
            Settings.Global.BROADCAST_OFFLOAD_CONSTANTS); // 卸载
    offloadConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
    // by default, no "slow" policy in this queue
    offloadConstants.SLOW_TIME = Integer.MAX_VALUE;
    mEnableOffloadQueue = SystemProperties.getBoolean(
            "persist.device_config.activity_manager_native_boot.offload_queue_enabled", false);
    mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
            "foreground", foreConstants, false);
    mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
            "background", backConstants, true);
    mBgOffloadBroadcastQueue = new BroadcastQueue(this, mHandler,
            "offload_bg", offloadConstants, true);
    mFgOffloadBroadcastQueue = new BroadcastQueue(this, mHandler,
            "offload_fg", foreConstants, true);
    mBroadcastQueues[0] = mFgBroadcastQueue;
    mBroadcastQueues[1] = mBgBroadcastQueue;
    mBroadcastQueues[2] = mBgOffloadBroadcastQueue;
    mBroadcastQueues[3] = mFgOffloadBroadcastQueue;
    
    // 初始化管理 Services 的 ActiveServices 物件
    mServices = new ActiveServices(this);
    // 初始化 ContentProvider
    mCpHelper = new ContentProviderHelper(this, true);
    // 包 WatchDog
    mPackageWatchdog = PackageWatchdog.getInstance(mUiContext);
    // 初始化 APP 错误日志记录组件
    mAppErrors = new AppErrors(mUiContext, this, mPackageWatchdog);
    mUidObserverController = new UidObserverController(mUiHandler);
    
    // 取得系統资料夹
    final File systemDir = SystemServiceManager.ensureSystemDir();
    // TODO: Move creation of battery stats service outside of activity manager service.
    // 创建电池统计服务
    mBatteryStatsService = new BatteryStatsService(systemContext, systemDir,
            BackgroundThread.get().getHandler());
    mBatteryStatsService.getActiveStatistics().readLocked();
    mBatteryStatsService.scheduleWriteToDisk();
    mOnBattery = DEBUG_POWER ? true
            : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
   
    // 创建进程统计分析服务,追踪统计进程的滥用、不良行为 
    mBatteryStatsService.getActiveStatistics().setCallback(this);
    mOomAdjProfiler.batteryPowerChanged(mOnBattery);
    mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
    mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);
    mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
    
    // 负责管理多用户
    mUserController = new UserController(this);
    mPendingIntentController = new PendingIntentController(
            mHandlerThread.getLooper(), mUserController, mConstants);
    
    // 初始化系统属性
    mUseFifoUiScheduling = SystemProperties.getInt("sys.use_fifo_ui", 0) != 0;
    mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
    mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
    
    // 赋予 ActivityTaskManager
    mActivityTaskManager = atm;
    
    // 初始化,內部会创建 ActivityStackSupervisor 类
    // ActivityStackSupervisor  会记录 Activity 状态信息,是 AMS 的核心类
    mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController,
            DisplayThread.get().getLooper());
    mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);
    mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext);
    mSdkSandboxSettings = new SdkSandboxSettings(mContext);
    
    // Watchdog 监听(若进程不正常则会被 Kill)
    Watchdog.getInstance().addMonitor(this);
    Watchdog.getInstance().addThread(mHandler);
    // bind background threads 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
    updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
    try {
        Process.setThreadGroupAndCpuset(BackgroundThread.get().getThreadId(),
                Process.THREAD_GROUP_SYSTEM);
        Process.setThreadGroupAndCpuset(
                mOomAdjuster.mCachedAppOptimizer.mCachedAppOptimizerThread.getThreadId(),
                Process.THREAD_GROUP_SYSTEM);
    } catch (Exception e) {
        Slog.w(TAG, "Setting background thread cpuset failed");
    }
    mInternal = new LocalService();
    mPendingStartActivityUids = new PendingStartActivityUids(mContext);
    mTraceErrorLogger = new TraceErrorLogger();
    mComponentAliasResolver = new ComponentAliasResolver(this);
}

AMS#setSystemProcess方法不只註冊自己 (AMS) 的 Server 到 Binder 驱动中,而是一系列与进程相关的服务,下表会提及几个常见的服务项目

// /ActivityManagerService.java
    public void setSystemProcess() {
        try {
            // 注册 AMS
            ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
                    DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
             // 注册 ProcessStatsService              
            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));
            if (MONITOR_CPU_USAGE) {
                ServiceManager.addService("cpuinfo", new CpuBinder(this),
                        /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
            }
            ServiceManager.addService("permission", new PermissionController(this));
            ServiceManager.addService("processinfo", new ProcessInfoService(this));
            ServiceManager.addService("cacheinfo", new CacheBinder(this));
            
            // 调用 PackageManagerService 的接口,查询包名为 android 的应用 App 的 ApplicationInfo 讯息
            ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
                    "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);

            // 往下分析 Activity#installSystemApplicationInfo 函数
            mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
            
            // 创建 ProcessRecord 对象,並保存 AMS 对象讯息
            synchronized (this) {
                ProcessRecord app = mProcessList.newProcessRecordLocked(info, info.processName,
                        false,
                        0,
                        new HostingRecord("system"));
                app.setPersistent(true);
                app.setPid(MY_PID);
                app.mState.setMaxAdj(ProcessList.SYSTEM_ADJ);
                app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
                addPidLocked(app);
                updateLruProcessLocked(app, false, null);
                updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
            }
            
            ... 省略部分
        } catch (PackageManager.NameNotFoundException e) {
            throw new RuntimeException(
                    "Unable to find android system package", e);
        }

        ... 省略部分
    }

Binder - AMS 功能

要知道所有的 AMS 功能最好是去查詢 IActivityManager,它里面包含所有 AMS 所提供的功能,以下分为几种分类描述
组件状态 - 管理: 4 大组件的管理,startActivity、startActivityAndWait、startService、stopService、removeContentProvider … 等等
组件状态 - 查询: 查看当前组件的运行狀況 getCallingAcitivty、getServices… 等等
Task 相关: Task 相关的函数,removeSubTask、remove Task … 等等
其他: getMemoryInfo、setDebugApp… 等等

AMS 重点类

AMS 相关类功能
ActivityStackSupervisor管理 Activity Stack
ClientLifecycleManagerAndroid 28 之後才加入,用來控制管理 Activity 的生命周期
ActivityStartActivity 启动器,也管理 Activity 的启动细节
ActivityStartController产生 ActivityStart 的实例,并且复用
ActivityTaskManagerService(简称 ATMS)Android 核心服务,负责启动四大组件
ActivityTaskManagerActivity 与 ATMS 跨进程通讯訊的接口,是 ATMS 的辅助类
ProcessRecord描述身分的数据
RecentTasks最近开启的 Activity
App 相关类功能
ActivityThreadApp 应用的进入点,启动主线程
ActivityThread#ApplicationThreadApplicationThread 是 ActivityThread 的内部类,继承 IApplication.Sub,它作为 APP 与 AMS 通讯的 Service 端
InstrumentationHook Activity 的启动、结束… 等等操作,应用 APP 与 AMS 的互交都透过Instrumentation
ActivityStack以 Stack 为单位 (AndroidManifest 的四种启动方式有关),负责管理多个 Activity

ProcessRecord 进程管理

ProcessRecord 类 - 进程相关讯息

参数说明
info : ApplicationInfoAndroidManifest.xml 中定义的 tag 相关信息
isolated : Booleanisolated 进程
uid : intuser id
pid : int进程 process id
gids : int[]群组 id
userId : intandroid 的多用户系统 id (就像是 windows 的多位使用者功能)
processName : String进程名,默认使用包名
uidRecord : UidRecord记录以使用的 uid
thread : IApplicationThread通过该物件 AMS 对 APP 发送讯息,该对象不为空代表该 APK 可使用
procStatFile:Stringproc 目录下每一个进程都有一个 以 pid 命名的目录文件,该文件记录进程的所有相关讯息,该目录是 Linux Kernel 创建的
compat : CompatibilityInfo兼容性信息
requiredAbi : Stringabi 讯息
instructionSet : String指令集合
mPkgList : PackageList包中运行的 APP
mPkgDeps : ArraySet当前进程运行依赖的包
ProcessRecord 类-描述进程组件
参数说明
maxAdj : int进程的 Adj 上限 (adjustment)
curRawAdj : int正在计算的 adj,这个值可能大于 maxAdj
ProcessRecord 类-描述进程组件(四大零组件相关)
参数说明
mWindowProcessController : WindowProcessController透过 WindowProcessController 管理所有 Activity
mServices : ProcessServiceRecord该进程内所有的 Service
mProviders : ProcessProviderRecord该进程内所有的 Provider
mReceivers : ProcessReceiverRecord该进程内所有的 Receiver

ActivityRecord - Activity

ActivityRecord 在记录一个 Activity 的所有讯息,它是 历史栈中的一个 Activity,内部纪录 ActivityInfo (AndroidManifest 设定)、task 服务

final class ActivityRecord extends WindowToken implements WindowManagerService.AppFreezeListener {

    // 所属的 Task 服务
    final ActivityTaskManagerService mAtmService;

    // AndroidManifest 设定的数值
    final ActivityInfo info;

    // WindowsManager token
    final ActivityRecord.Token appToken;

    // 私有化构造函数
    // 透过 builder 模式建构 ActivityRecord 对象
    private ActivityRecord(ActivityTaskManagerService _service, WindowProcessController _caller,
            int _launchedFromPid, int _launchedFromUid, String _launchedFromPackage,
            @Nullable String _launchedFromFeature, Intent _intent, String _resolvedType,
            ActivityInfo aInfo, ... /* 省略部份*/ ) {
        ... 省略部分
    }
}
// ActivityStarter.java

// Last activity record we attempted to start
private ActivityRecord mLastStartActivityRecord;

private int executeRequest(Request request) {
    ...省略 Request 分析

    // 透過 Builder 創建 AcitiviyRecord
    final ActivityRecord r = new ActivityRecord.Builder(mService)
        .setCaller(callerApp)        // 設定各種參數
        .setLaunchedFromPid(callingPid)
        .setLaunchedFromUid(callingUid)
        .setLaunchedFromPackage(callingPackage)
        .setLaunchedFromFeature(callingFeatureId)
        .setIntent(intent)
        .setResolvedType(resolvedType)
        .setActivityInfo(aInfo)
        .setConfiguration(mService.getGlobalConfiguration())
        .setResultTo(resultRecord)
        .setResultWho(resultWho)
        .setRequestCode(requestCode)
        .setComponentSpecified(request.componentSpecified)
        .setRootVoiceInteraction(voiceSession != null)
        .setActivityOptions(checkedOptions)
        .setSourceRecord(sourceRecord)
        .build();

    // 當前 Activity
    mLastStartActivityRecord = r;
    
    ... 省略部分
}

启动 Activity - 调用ActivityTaskManagerService

ActivityTaskManagerService 它也是一个系统服务(注册在 Binde r驱动中),App 端如果要调用就必须透过代理,这个代理就是 ActivityTaskManager

// Activity.java

public class Activity extends ContextThemeWrapper
        implements LayoutInflater.Factory2,
        Window.Callback, KeyEvent.Callback,
        ...省略部分接口 {

    /*package*/ ActivityThread mMainThread;
    private Instrumentation mInstrumentation;    

    @Override
    public void startActivity(Intent intent) {
        this.startActivity(intent, null);
    }

    @Override
    public void startActivity(Intent intent, @Nullable Bundle options) {

        ... 省略部分

        // @ 分析 startActivityForResult 方法
        if (options != null) {
            startActivityForResult(intent, -1, options);
        } else {
            startActivityForResult(intent, -1);
        }
    }

    public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
            @Nullable Bundle options) {
        if (mParent == null) {
            options = transferSpringboardActivityOptions(options);

            // @ 分析 execStartActivity 方法 
            Instrumentation.ActivityResult ar =
                mInstrumentation.execStartActivity(
                    this,
                    // ApplicationThread
                    mMainThread.getApplicationThread(), 
                    mToken, this,
                    intent, requestCode, options);

            ... 省略部分

        } else {
            ... 省略部分
        }
    }
}


// ---------------------------------------------------------
// ActivityThread .java

public final class ActivityThread extends ClientTransactionHandler
    implements ActivityThreadInternal {


    // 一个应用行程只有一个
    final ApplicationThread mAppThread = new ApplicationThread();

    public ApplicationThread getApplicationThread()
    {
        return mAppThread;
    }

    private class ApplicationThread extends IApplicationThread.Stub {
        ... 省略细节
    }
}
// Instrumentation.java
public class Instrumentation {

    public ActivityResult execStartActivity(
            Context who, 
            IBinder contextThread, // IApplicationThread
            IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {
        
        IApplicationThread whoThread = (IApplicationThread) contextThread;

        ... 省略部分

        try {
            ...省略部分
            
            // 启动了 ActivityTaskManager#startActivity 函数
            // whoThread 就是 IApplicationThread
            int result = ActivityTaskManager.getService().startActivity(whoThread,
                    who.getBasePackageName(), who.getAttributionTag(), intent,
                    intent.resolveTypeIfNeeded(who.getContentResolver()), token,
                    target != null ? target.mEmbeddedID : null, requestCode, 0, null, options);
            
            // 检查 AMS 检查结果
            checkStartActivityResult(result, intent);
        } catch (RemoteException e) {
            throw new RuntimeException("Failure from system", e);
        }
        return null;
    }
}
// ActivityTaskManagerService.java

// SystemService 启动的系统进程
// IActivityTaskManager.Stub 是 Service 端的实作
public class ActivityTaskManagerService extends IActivityTaskManager.Stub {    // IActivityTaskManager 是 IDE 自動生成類

    @Override
    public final int startActivity(IApplicationThread caller, String callingPackage,
            String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
            String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
            Bundle bOptions) {
        return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
                resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions,
                UserHandle.getCallingUserId());
    }

}