一、简介

AMS全称ActivityManagerService,它作为一个体系服务办理着ActivityServiceContentProviderBroadcastReceiver这四大组件的发动,能够说ActivityManagerService服务对于Android体系来讲非常的重要。文章将从AMS的发动AMS怎么办理Activity的发动这两方面来剖析AMS在Android体系中所发挥的效果。

二、AMS的发动

首先AMS的发动是在SystemServer中完结的,SystemServer担任发动各式各样的体系服务,这儿就包括ActivityManagerService

SystemServer#startBootstrapServices
private void startBootstrapServices() {
    //创立AMS,并经过体系服务办理器发动AMS
    mActivityManagerService = mSystemServiceManager.startService(
            ActivityManagerService.Lifecycle.class).getService();
    //设置SystemServiceManager     
    mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
    //设置Installer服务
    mActivityManagerService.setInstaller(installer);
    //初始化与之相关的PowerManager
    mActivityManagerService.initPowerManagement();
    //将AMS和一些需求的服务注册到ServiceManager中(ServiceManager是由Init进程发动的)
    mActivityManagerService.setSystemProcess();
}
SystemServer#startCoreServices
private void startCoreServices() {
    //设置UsageStatsManager
    mActivityManagerService.setUsageStatsManager(
           LocalServices.getService(UsageStatsManagerInternal.class));
}
SystemServer#startOtherServices
private void startOtherServices() {
    //为SystemServer进程装置ContentProvider目标
    mActivityManagerService.installSystemProviders();
    //设置WindowManager(WMS)
    mActivityManagerService.setWindowManager(wm);
    if (safeMode) {
        //设置安全模式
        mActivityManagerService.enterSafeMode();
    } 
    if (safeMode) {
        //设置安全模式的View
        mActivityManagerService.showSafeModeOverlay();
    }
    //AMS发动结束
    mActivityManagerService.systemReady(() -> {
        //标记SystemServer的阶段
        mSystemServiceManager.startBootPhase(
                SystemService.PHASE_ACTIVITY_MANAGER_READY);
        try {
            //敞开独立的线程监听Native崩溃
            mActivityManagerService.startObservingNativeCrashes();
            ....
            敞开WebView更新服务
            发动体系ui
            设置各种服务的onReady
            ....
        }
    }
}

上面三个办法中的代码便是SystemServer中关于ActivityManagerService的相关流程的中心代码。办法在SystemServer中的调用次序是startBootstrapServices->startCoreServices->startOtherServices。整体的流程能够概括为几个中心的进程:
1)创立AMS并发动。
2)将AMS注册到ServiceManager中。
3)为SystemServer进程装置ContentProvider目标。
4)标记AMS发动结束。

2.1创立并发动AMS

首先来从SystemServiceManager的startService办法下手。

SystemServiceManager#startService
public <T extends SystemService> T startService(Class<T> serviceClass) {
    try {
        //获取类名
        final String name = serviceClass.getName();
        final T service;
        try {
            Constructor<T> constructor = serviceClass.getConstructor(Context.class);
            //反射创立目标
            service = constructor.newInstance(mContext);
        } 
        ....
        startService(service);
        return service;
    }
    ....
}
SystemServiceManager#startService
public void startService(@NonNull final SystemService service) {
    //添加到Service的集合中
    mServices.add(service);
    //时间戳
    long time = SystemClock.elapsedRealtime();
    try {
        //发动服务
        service.onStart();
    }
    ....
    //超时警告
    warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
}

从以上代码能够看出SystemServiceManager经过传入的Class反射创立目标,最终调用service的onStart办法发动服务,这儿传入的类型便是ActivityManagerService.Lifecycle.class。

public static final class Lifecycle extends SystemService {
    private final ActivityManagerService mService;
    public Lifecycle(Context context) {
        super(context);
        //创立ActivityManagerService
        mService = new ActivityManagerService(context);
    }
    @Override
    public void onStart() {
        //发动服务,上方service.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() {
        //回来ActivityManagerService实例目标
        return mService;
    }
}

能够看到ActivityManagerService.Lifecycle承继于SystemService,经过Lifecycle来完结ActivityManagerService目标的创立、发动和实例的回来。接下来剖析ActivityManagerService的结构办法和start办法。

public ActivityManagerService(Context systemContext) {
    ....
    //获取Context
    mContext = systemContext;
    //获取体系ActivityThread
    mSystemThread = ActivityThread.currentActivityThread();
    //获取体系ui Context
    mUiContext = mSystemThread.getSystemUiContext();
    ....
    //创立一个HandlerThread来接收AMS发送的音讯
    mHandlerThread = new ServiceThread(TAG,
            THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
    mHandlerThread.start();
    mHandler = new MainHandler(mHandlerThread.getLooper());
    mUiHandler = mInjector.getUiHandler(this);
    //创立与发动proc线程
    mProcStartHandlerThread = new ServiceThread(TAG + ":procStart",
            THREAD_PRIORITY_FOREGROUND, false /* allowIo */);
    mProcStartHandlerThread.start();
    mProcStartHandler = new Handler(mProcStartHandlerThread.getLooper());
    //一些办理的常量
    mConstants = new ActivityManagerConstants(this, mHandler);
    //前台播送行列
    mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
            "foreground", BROADCAST_FG_TIMEOUT, false);
    //后台播送行列        
    mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
            "background", BROADCAST_BG_TIMEOUT, true);
    mBroadcastQueues[0] = mFgBroadcastQueue;
    mBroadcastQueues[1] = mBgBroadcastQueue;
    //初始化Service相关的容器
    mServices = new ActiveServices(this);
    //初始化ProviderMap相关的容器
    mProviderMap = new ProviderMap(this);
    mAppErrors = new AppErrors(mUiContext, this);
    //创立data/system/目录
    File dataDir = Environment.getDataDirectory();
    File systemDir = new File(dataDir, "system");
    systemDir.mkdirs();
    //初始化电量计算服务相关的信息
    mBatteryStatsService = new BatteryStatsService(systemContext, systemDir, mHandler);
    mBatteryStatsService.getActiveStatistics().readLocked();
    mBatteryStatsService.scheduleWriteToDisk();
    mOnBattery = DEBUG_POWER ? true
            : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
    mBatteryStatsService.getActiveStatistics().setCallback(this);
    //初始化体体系计服务,用于计算体系的运转信息
    mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
    mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);
    mGrantFile = new AtomicFile(new File(systemDir, "urigrants.xml"), "uri-grants");
    //创立体系的第一个user,userID为0,该用户具有办理员权限
    mUserController = new UserController(this);
    mVrController = new VrController(this);
    //获取opengle的版别
    GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
        ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
    ....
    //初始化StackSupervisor,该类是Activity发动和调度的中心类
    mStackSupervisor = createStackSupervisor();
    mActivityStartController = new ActivityStartController(this);
    mRecentTasks = createRecentTasks();
    mStackSupervisor.setRecentTasks(mRecentTasks);
    //查看cpu的线程
    mProcessCpuThread = new Thread("CpuTracker");
    ....
}

从上能够看出,ActivityManagerService的结构办法做了很多的初始化相关操作。首先记录运转需求的Context和ActivityThread。然后初始化播送、服务和contentProvider的相关存储变量,还会进行初始化电量计算服务等信息,还创立了ActivityStackSupervisor用来办理和调度Activity。

ActivityManagerService#start
private void start() {
    //发动cpu查看线程
    mProcessCpuThread.start();
    //发布电量计算服务
    mBatteryStatsService.publish();
    mAppOpsService.publish(mContext);
    //注册当前的服务到LocalServices,LocalService是AMS的内部类,直接对外露出AMS的运用
    LocalServices.addService(ActivityManagerInternal.class, new LocalService());
    ....
}

AMS的start相对简略,便是敞开了几个相关服务和cpu的查看并将本身直接注册到LocalServices中。

2.2将AMS注册到ServiceManager中

接下来剖析怎么将AMS注册到ServiceManager中,这儿需求来剖析AMS的setSystemProcess办法。

ActivityManagerService#setSystemProcess
public void setSystemProcess() {
    try {
        //将AMS注册到ServiceManager中,key为“activity”
        ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
                DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
        //注册各式各样的服务到ServiceManager中       
        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));
        //从PackageManager中查询包名为android的application,即framework-res的Application信息
        ApplicationInfo info = mContext.getPackageManager().getApplicationInfo
                "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
        //将application信息装备到开始创立的activityThread中        
        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();
        }
    } 
    .... 
}

setSystemProcess办法最中心的一点便是将AMS注册到ServiceManager中,这样后续运用AMS的地方就能够经过ServiceManager来获取到了。

2.3为SystemServer进程装置ContentProvider目标

Android体系中有很多装备信息都需求保存,这些信息是保存在SettingsProvider中,而这个SettingsProvider也是运转在SystemServer进程中的,由于SystemServer进程依赖SettingsProvider,放在一个进程中能够减少进程间通讯的效率丢失。

public final void installSystemProviders() {
    List<ProviderInfo> providers;
    synchronized (this) {
        //找到名称为”System”的进程,便是上一步创立的processRecord目标
        ProcessRecord app = mProcessNames.get("system", SYSTEM_UID);
        //找到一切和system进程相关的ContentProvider
        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) {
                    //再次确认进程为system的provider,把不是该进程provider移除
                    providers.remove(i);
                }
            }
        }
    }
    if (providers != null) {
        //把provider装置到体系的ActivityThread中
        mSystemThread.installSystemProviders(providers);
    }
    synchronized (this) {
        //设置已装置标记位
        mSystemProvidersInstalled = true;
    }
    //初始化各种Observer
    mConstants.start(mContext.getContentResolver());
    mCoreSettingsObserver = new CoreSettingsObserver(this);
    mFontScaleSettingObserver = new FontScaleSettingObserver();
    mDevelopmentSettingsObserver = new DevelopmentSettingsObserver();
    GlobalSettingsToPropertiesMapper.start(mContext.getContentResolver());
    RescueParty.onSettingsProviderPublished(mContext);
}

找到名称为system的进程目标,便是SystemServer进程,然后依据进程目标去查询一切有关的ContentProvider,调用体系进程的主线程ActivityThread装置一切相关的ContentProvider

2.4标记AMS发动结束

AMS的发动最终阶段来到systemReady办法。

public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
    synchronized(this) {
        if (mSystemReady) {
            //回调SystemServer
            if (goingCallback != null) {
                goingCallback.run();
            }
            return;
        }
        mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_CANT_SAVE_STATE);
        mLocalDeviceIdleController
                = LocalServices.getService(DeviceIdleController.LocalService.class);
        mAssistUtils = new AssistUtils(mContext);
        //调用各种服务的Ready办法
        mVrController.onSystemReady();
        mUserController.onSystemReady();
        mRecentTasks.onSystemReadyLocked();
        mAppOpsService.systemReady();
        mSystemReady = true;
    }
    try {
        //获取设备识别字符
        sTheRealBuildSerial = IDeviceIdentifiersPolicyService.Stub.asInterface(
                ServiceManager.getService(Context.DEVICE_IDENTIFIERS_SERVICE))
                .getSerial();
    } catch (RemoteException e) {}
    //搜集目前已经存在的进程
    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);
            }
        }
    }
    //销毁在AMS发动之前存在的进程
    synchronized(this) {
        if (procsToKill != null) {
            for (int i=procsToKill.size()-1; i>=0; i--) {
                ProcessRecord proc = procsToKill.get(i);
                Slog.i(TAG, "Removing system update proc: " + proc);
                removeProcessLocked(proc, true, false, "system update done");
            }
        }
        mProcessesReady = true;
    }
    ....
    //初始化Settings变量
    retrieveSettings();
    //获取UserId
    final int currentUserId = mUserController.getCurrentUserId();
    synchronized (this) {
        //读取权限
        readGrantedUriPermissionsLocked();
    }
    //获取PowerManager并注册监听
    final PowerManagerInternal pmi = LocalServices.getService(PowerManagerInternal.class);
    if (pmi != null) {
        pmi.registerLowPowerModeObserver(ServiceType.FORCE_BACKGROUND_CHECK,
                state -> updateForceBackgroundCheck(state.batterySaverEnabled));
        updateForceBackgroundCheck(
                pmi.getLowPowerState(ServiceType.FORCE_BACKGROUND_CHECK).batterySaverEnabled);
    }
    //调用callback办法,该办法在systemServer代码中实现
    if (goingCallback != null) goingCallback.run();
    //给BatteryStatsService发送状况
    mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,
            Integer.toString(currentUserId), currentUserId);
    mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,
            Integer.toString(currentUserId), currentUserId);
    //SystemServiceManager设置UserId
    mSystemServiceManager.startUser(currentUserId);
    synchronized (this) {
    ....
    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();
        }
    }
        //敞开HomeActivity
        startHomeActivityLocked(currentUserId, "systemReady");
        ....
        //最上层Activity获取焦点
        mStackSupervisor.resumeFocusedStackTopActivityLocked();
        mUserController.sendUserSwitchBroadcasts(-1, currentUserId);
       ....
    }
}

SystemReady办法代码量也比较大,主要做了几种作业:
1.调用了几种AMS所需求的服务的onSystemReady回调。
2.移除并杀死了那些不该在AMS之前发动的进程。
3.回调SystemServer当前服务预备已经完结,SystemServer中会发动体系ui,敞开WbView更新和调用各种服务的onReday。
4.发动HomeActivity。

三、AMS发动Activity

上面剖析了在SystemServer中AMS是怎么发动的,AMS办理着四大组件的发动,这儿以Activity为例简略剖析一下AMS在Activity发动进程中所起到的效果。

Activity#startActivityForResult
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
        @Nullable Bundle options) {
        //其实在Activity中startActivity办法最终都是调用到startActivityForResult,所以这儿直接从startActivityForResult为进口进行剖析。
        ....
        //调用到Instrumentation的execStartActivity办法
        Instrumentation.ActivityResult ar =
            mInstrumentation.execStartActivity(
                this, mMainThread.getApplicationThread(), mToken, this,
                intent, requestCode, options);
        ....        
}
Instrumentation#execStartActivity
public ActivityResult execStartActivity(
    Context who, IBinder contextThread, IBinder token, String target,
    Intent intent, int requestCode, Bundle options) {
    ....
        //调用ActivityManager.getService获取AMS,并调用AMS的startActivity办法
        int result = ActivityManager.getService()
            .startActivity(whoThread, who.getBasePackageName(), intent,
                    intent.resolveTypeIfNeeded(who.getContentResolver()),
                    token, target, requestCode, 0, null, options);
   ....                 
}
ActivityManager#getService
public static IActivityManager getService() {
    return IActivityManagerSingleton.get();
}
private static final Singleton<IActivityManager> IActivityManagerSingleton =
        new Singleton<IActivityManager>() {
            @Override
            protected IActivityManager create() {
                //经过ServiceManager获取AMS,之前AMS发动的流程中注册到了ServiceManager中
                final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
                final IActivityManager am = IActivityManager.Stub.asInterface(b);
                return am;
            }
        };

从上面的代码能够看出startActivity办法经过调用来到了Instrumentation的execStartActivity最终获取到了AMS目标,即ActivityManagerService。之后调用的便是ActivityManagerService的startActivity办法了。

ActivityManagerService#startActivity
public final int startActivity(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, Bundle options) {
        return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
            resultWho, requestCode, startFlags, profilerInfo, options,
            UserHandle.getCallingUserId());
    }
ActivityManagerService#startActivityAsUser    
public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, Bundle options, int userId) {
        //调用到了mStackSupervisor来办理Activity
        return mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent,
                resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
                profilerInfo, null, null, options, false, userId, null, null);
    }  

现在办法调用来到了ActivityManagerService中了,整体Activity的发动流程仍是挺复杂的,会涉及到Activity的栈办理、app进程办理等流程,这儿就不进行代码剖析了,感兴趣的能够看一下这篇文章Activity发动流程

四、总结

AMS最为Android体系中的非常中心服务,办理着四大组件的发动,由SystemServer进程来发动。大体发动流程分为几步:
1. 在SystemServer服务中创立并发动AMS。
2. 调用AMS的结构办法和start办法,对AMS必要的内容进行初始化。
3. 将AMS注册到ServiceManager中,ServiceManager作为大管家办理AMS服务。AMS的运用直接经过ServiceManager来获取。
4. 将settingsProvider加载到体系进程systemServer中。
5. 在AMS发动完结后敞开体系HomeActivity和systemUI。

注:以上剖析根据API Level 28

参考文章
ActivityManagerService发动进程
AMS发动流程