美文网首页
Android ActivityManagerService--

Android ActivityManagerService--

作者: DarcyZhou | 来源:发表于2023-10-26 09:22 被阅读0次

    本文转自:

    本文基于Android 11.0源码分析

    前言

      ActivityManagerService简称AMS,负责管理四大组件的生命周期以及应用程序进程调度,其中Activity相关实际上由ATMS负责。它有自己的IActivityManager.aidl、ActivityManagerInternal,属于server/am目录下。

      ActivityTaskManagerService简称ATMS,负责管理Activities和Activity相关容器(Task,Stacks,Display),也有自己的IActivityTaskManager.aidl、ActivityManagerInternal,在server/wm目录下。

      AMS和ATMS启动流程,如下面所示:

    AMS01.PNG

    1.SystemServer启动

      SystemServer是Zygote第一个Fork的进程,这里只分析SystemServer启动流程中AMS相关的逻辑,启动流程可以分为如下几个步骤:

    1. 初始化SystemContext;
    2. 创建SystemServiceManage对象,用来启动后面的服务;
    3. 启动系统服务,共分为三种系统服务:系统引导服务(Boot Service)、核心服务(Core Service)和其他服务(Other Service);
    4. 在引导服务(Boot Service)中启动ATMS和AMS服务;
    5. 在其他服务(Other Service)中完成AMS的最后工作systemReady。
    // frameworks/base/services/java/com/android/server/SystemServer.java
        public static void main(String[] args) {
            new SystemServer().run();
        }
    //--------------
        private void run() {
                 ...
                // Initialize the system context.
                createSystemContext();// 1.初始化 System Context
    
                // Call per-process mainline module initialization.
                ActivityThread.initializeMainlineModules();
    
                // 2.创建SystemServiceManager对象,用来启动后面的服务
                mSystemServiceManager = new SystemServiceManager(mSystemContext);
                mSystemServiceManager.setStartInfo(mRuntimeRestart,
                        mRuntimeStartElapsedTime, mRuntimeStartUptime);
                LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
    
                ...
    
            //3.启动服务
            try {
                t.traceBegin("StartServices");
                startBootstrapServices(t);   // 启动引导服务
                startCoreServices(t);        // 启动核心服务
                startOtherServices(t);       // 启动其他服务
            } catch (Throwable ex) {
            ...
        }
    

    下面对这三个过程逐步分析。

    1.1 初始化System Context

      在SystemServer的run()方法中,在启动AMS之前,调用了createSystemContext()方法,主要用来是初始化 System Context和SystemUI Context,并设置主题。
      当SystemServer调用createSystemContext()完毕后,完成以下两个内容:

    1. 得到了一个ActivityThread对象,它代表当前进程 (此时为系统进程) 的主线程;
    2. 得到了一个Context对象,对于SystemServer而言,它包含的Application运行环境与framework-res.apk有关。
    // frameworks/base/services/java/com/android/server/SystemServer.java 
        private void createSystemContext() {
            //1.创建ActivityThread对象
            ActivityThread activityThread = ActivityThread.systemMain();
            //2.获取system context
            mSystemContext = activityThread.getSystemContext();
            //3.设置系统主题
            mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
    
            //4.获取systemui context
            final Context systemUiContext = activityThread.getSystemUiContext();
            //5.设置systemUI 主题
            systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
        }
    

    1.1.1 systemMain()

      systemMain函数主要作用是: 创建ActivityThread对象,然后调用该对象的attach函数。

    // frameworks/base/core/java/android/app/ActivityThread.java
        public static ActivityThread systemMain() {
            // The system process on low-memory devices do not get to use hardware
            // accelerated drawing, since this can add too much overhead to the
            // process.
            if (!ActivityManager.isHighEndGfx()) {
                ThreadedRenderer.disable(true);
            } else {
                ThreadedRenderer.enableForegroundTrimming();
            }
            // 1.创建ActivityThread对象
            ActivityThread thread = new ActivityThread();
            // 2.调用attach方法
            thread.attach(true, 0);
            return thread;
        }
    

    (1)创建ActivityThread对象

      ActivityThread是Android Framework中一个非常重要的类,它代表一个应用进程的主线程,其职责就是调度及执行在该线程中运行的四大组件。 注意到此处的ActivityThread创建于SystemServer进程中。

      由于SystemServer中也运行着一些系统APK,例如framework-res.apk、SettingsProvider.apk等,因此也可以认为SystemServer是一个特殊的应用进程。

      AMS负责管理和调度进程,因此AMS需要通过Binder机制和应用进程通信。 为此,Android提供了一个IApplicationThread接口,该接口定义了AMS和应用进程之间的交互函数。

      ActivityThread的构造函数比较简单,获取ResourcesManager的单例对象,比较关键的是它的成员变量:

    // frameworks/base/core/java/android/app/ActivityThread.java
    public final class ActivityThread extends ClientTransactionHandler {
    
        ...
        //定义了AMS与应用通信的接口,拿到ApplicationThread的对象
        final ApplicationThread mAppThread = new ApplicationThread();
    
        //拥有自己的looper,说明ActivityThread确实可以代表事件处理线程
        final Looper mLooper = Looper.myLooper();
    
        //H继承Handler,ActivityThread中大量事件处理依赖此Handler
        final H mH = new H();
    
        //用于保存该进程的ActivityRecord
        final ArrayMap<IBinder, ActivityClientRecord> mActivities = new ArrayMap<>();
    
        //用于保存进程中的Service
        final ArrayMap<IBinder, Service> mServices = new ArrayMap<>();
    
        用于保存进程中的Application
        final ArrayList<Application> mAllApplications
            = new ArrayList<Application>();
        //构造函数
        @UnsupportedAppUsage
        ActivityThread() {
            mResourcesManager = ResourcesManager.getInstance();
        }
    }
    

    (2)调用attach()方法

      对于系统进程而言,ActivityThread的attach函数最重要的工作就是创建了Instrumentation、Application和Context。

    // frameworks/base/core/java/android/app/ActivityThread.java
        private void attach(boolean system, long startSeq) {
            sCurrentActivityThread = this;
            mSystemThread = system;
            //系统进程system为true
            if (!system) {
                // 应用进程处理流程
            } else {
                // Don't set application object here -- if the system crashes,
                // we can't display an alert, we just want to die die die.
                android.ddm.DdmHandleAppName.setAppName("system_process",
                        UserHandle.myUserId());
                try {
                    //系统进程的处理流程,该情况只在SystemServer中处理
                    //1.创建Instrumentation
                    mInstrumentation = new Instrumentation();
                    mInstrumentation.basicInit(this);
                    //2.创建系统Context
                    ContextImpl context = ContextImpl.createAppContext(
                            this, getSystemContext().mPackageInfo);
                    //3.创建Application
                    mInitialApplication = context.mPackageInfo.makeApplication(true, null);
                    mInitialApplication.onCreate();
                } catch (Exception e) {
                    throw new RuntimeException(
                            "Unable to instantiate Application():" + e.toString(), e);
                }
            }
            ...
        }
    
    • Instrumentation

      Instrumentation是Android中的一个工具类,当该类被启用时,它将优先于应用中其它的类被初始化。 此时,系统先创建它,再通过它创建其它组件。

    mInstrumentation = new Instrumentation();
    mInstrumentation.basicInit(this);
    
    • Context

      Context是Android中的一个抽象类,用于维护应用运行环境的全局信息。通过Context可以访问应用的资源和类,甚至进行系统级的操作,例如启动Activity、发送广播等。
      ActivityThread的attach函数中,通过下面的代码创建出系统应用对应的Context:

    ContextImpl context = ContextImpl.createAppContext(this, getSystemContext().mPackageInfo);
    
    • Application

      Android中Application类用于保存应用的全局状态。在ActivityThread中,针对系统进程,通过下面的代码创建了初始的Application:

    mInitialApplication = context.mPackageInfo.makeApplication(true, null);
    mInitialApplication.onCreate();
    

    1.1.2 getSystemContext()

      再回到createSystemContext()方法中初始化SystemContext的过程中,到getSystemContext()方法,该方法主要是创建并返回System Context。

    // frameworks/base/services/java/com/android/server/SystemServer.java 
        public ContextImpl getSystemContext() {
            synchronized (this) {
                if (mSystemContext == null) {
                    //调用ContextImpl的静态函数createSystemContext()
                    mSystemContext = ContextImpl.createSystemContext(this);
                }
                return mSystemContext;
            }
        }
    

    这里直接调用了ContextImpl中的静态方法:

    // frameworks/base/core/java/android/app/ContextImpl.java
        static ContextImpl createSystemContext(ActivityThread mainThread) {
            //创建LoadedApk类,代表一个加载到系统中的APK
            //注意此时的LoadedApk只是一个空壳
            //PKMS还没有启动,无法得到有效的ApplicationInfo
            LoadedApk packageInfo = new LoadedApk(mainThread);
            //拿到ContextImpl的对象
            ContextImpl context = new ContextImpl(null, mainThread, packageInfo, null, null, null, null,
                    0, null, null);
            //初始化资源信息
            context.setResources(packageInfo.getResources());
            context.mResources.updateConfiguration(context.mResourcesManager.getConfiguration(),
                    context.mResourcesManager.getDisplayMetrics());
            context.mIsSystemOrSystemUiContext = true;
            return context;
        }
    

    createSystemContext()的内容就是创建一个LoadedApk,然后初始化一个ContextImpl对象。 创建的LoadApk对应packageName为”android”,也就是framwork-res.apk。 由于该APK仅供SystemServer进程使用,因此创建的Context被定义为System Context。

      现在该LoadedApk还没有得到framwork-res.apk实际的信息。当PKMS启动,完成对应的解析后,AMS将重新设置这个LoadedApk。

    1.1.3 getSystemUiContext()

      这个方法是用来获取SystemUi的Context,具体流程与getSystemContext()方法类似。

    // frameworks/base/services/java/com/android/server/SystemServer.java 
        public ContextImpl getSystemUiContext() {
            synchronized (this) {
                if (mSystemUiContext == null) {
                    mSystemUiContext = ContextImpl.createSystemUiContext(getSystemContext());
                }
                return mSystemUiContext;
            }
        }
    

    然后再调用ContextImpl的createSystemUiContext()方法:

    // frameworks/base/core/java/android/app/ContextImpl.java
        static ContextImpl createSystemUiContext(ContextImpl systemContext, int displayId) {
            final LoadedApk packageInfo = systemContext.mPackageInfo;
            // 创建context
            ContextImpl context = new ContextImpl(null, systemContext.mMainThread, packageInfo, null,
                    null, null, null, 0, null, null);
            context.setResources(createResources(null, packageInfo, null, displayId, null,
                    packageInfo.getCompatibilityInfo(), null));
            context.updateDisplay(displayId);
            context.mIsSystemOrSystemUiContext = true;
            return context;
        }
    

    1.2 创建SystemServiceManager

      再回到SystemServer启动的run()方法中,在调用createSystemContext()方法初始化System Context后,就是创建SystemServiceManager对象。

    // frameworks/base/services/java/com/android/server/SystemServer.java
        private void run() {
            ...
            //1.创建SystemServiceManager对象
            mSystemServiceManager = new SystemServiceManager(mSystemContext);
            mSystemServiceManager.setStartInfo(mRuntimeRestart,
                    mRuntimeStartElapsedTime, mRuntimeStartUptime);
            //2.启动SystemServiceManager服务
            LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
            ...
        }
    

    1.2.1 SystemServiceManager()

      SystemServiceManager对象主要用于管理SystemService的创建、启动等生命周期,SystemService 类是一个抽象类。

    // frameworks/base/services/core/java/com/android/server/SystemServiceManager.java
    public class SystemServiceManager {
        ...
        private final Context mContext;
        private final ArrayList<SystemService> mServices = new ArrayList<SystemService>();
        ...
        SystemServiceManager(Context context) {
            mContext = context;
        }
    
        public SystemService startService(String className) {
            //通过反射根据类名,拿到类对象
            final Class<SystemService> serviceClass = loadClassFromLoader(className,
                    this.getClass().getClassLoader());
            return startService(serviceClass);
        }
    //------------------------
        private static Class<SystemService> loadClassFromLoader(String className,
                ClassLoader classLoader) {
            try {
                return (Class<SystemService>) Class.forName(className, true, classLoader);
            } catch (ClassNotFoundException ex) {
            ...
        }
    //------------------------
        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);
                } catch (InstantiationException ex) {
                ...
                startService(service);
                return service;
            } finally {
                Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
            }
        }
    //------------------------
        public void startService(@NonNull final SystemService service) {
            // Register it.
            mServices.add(service);
            // Start it.
            long time = SystemClock.elapsedRealtime();
            try {
                service.onStart(); //调用各个服务中的onStart()方法完成服务启动
            } catch (RuntimeException ex) {
                throw new RuntimeException("Failed to start service " + service.getClass().getName()
                        + ": onStart threw an exception", ex);
            }
            warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
        }
        ...
    }
    

    在SystemServiceManager中都是通过反射创建SystemService中对象的,而且在 startService(@NonNull final SystemService service)方法中,会将SystemService添加到mServices 中,并调用 onStart() 方法。

    1.2.2 addService()

      回到《1.2 创建SystemServiceManager》中,在创建完SystemServiceManager对象后,会调用addService()方法:

    // frameworks/base/core/java/com/android/server/LocalServices.java
    public final class LocalServices {
        private LocalServices() {}
    
        private static final ArrayMap<Class<?>, Object> sLocalServiceObjects =
                new ArrayMap<Class<?>, Object>();
    
        //返回实现指定接口的本地服务实例对象
        @SuppressWarnings("unchecked")
        public static <T> T getService(Class<T> type) {
            synchronized (sLocalServiceObjects) {
                return (T) sLocalServiceObjects.get(type);
            }
        }
    
        //将指定接口的服务实例添加到本地服务的全局注册表中
        public static <T> void addService(Class<T> type, T service) {
            synchronized (sLocalServiceObjects) {
                if (sLocalServiceObjects.containsKey(type)) {
                    throw new IllegalStateException("Overriding service registration");
                }
                sLocalServiceObjects.put(type, service);
            }
        }
    
        //删除服务实例,只能在测试中使用
        @VisibleForTesting
        public static <T> void removeServiceForTest(Class<T> type) {
            synchronized (sLocalServiceObjects) {
                sLocalServiceObjects.remove(type);
            }
        }
    }
    

    1.3 启动核心服务

      回到《1.SystemServer启动》中,在处理完SystemServiceManager对象后,回去启动三个服务,这里只关注核心服务启动:startBootstrapServices()。

      在该方法中启动引导服务,在其中启动了ATM和AMS服务,通过AMS安装Installer、初始化Power,设置系统进程等。

    // frameworks/base/services/java/com/android/server/SystemServer.java
        private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
    
            //1.启动ActivityTaskManagerService服务,简称ATMS
            //Android10新引入功能,用来管理Activity的启动、调度等功能
            ActivityTaskManagerService atm = mSystemServiceManager.startService(
                    ActivityTaskManagerService.Lifecycle.class).getService();
            //2.启动服务 ActivityManagerService,简称AMS
            mActivityManagerService = ActivityManagerService.Lifecycle.startService(
                    mSystemServiceManager, atm);
            //3.把ssm和installer赋值给ActivityManagerService
            mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
            mActivityManagerService.setInstaller(installer);
            //4\. 利用atm,获取WindowManagerGlobalLock
            mWindowManagerGlobalLock = atm.getGlobalLock();
            t.traceEnd();
            //5.初始化PowerManager
            mActivityManagerService.initPowerManagement();
            //6.设置系统进程
            mActivityManagerService.setSystemProcess();
            ...
        }
    

    到这里SystemServer已经开启去启动服务了,这篇文档关注的ATMS和AMS的启动过程在下面作详细的分析。

    2.ActivityTaskMangerService启动过程

      ActivityTaskManagerService简称ATM,Android10中引入新功能,用来管理Activity的启动、调度等功能。紧接上面的流程,在SystemServer在startBootstrapServices()方法中会去启动ATMS:

    // frameworks/base/services/java/com/android/server/SystemServer.java
    private void startBootstrapServices() {
        ...
        //启动ATMS
        ActivityTaskManagerService atm = mSystemServiceManager.startService(
                ActivityTaskManagerService.Lifecycle.class).getService();
        ...
    }
    

    从《1.2.1 SystemServiceManager()》中,可以知道SystemServiceManager.startService()最终调用的是启动对象中的onStart方法,因此ATM启动,这里最终会调用ActivityTaskManagerService.Lifecycle.onStart()来启动ATMS服务:

    // frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
        //静态内部类,继承SystemService,说明它是一个系统service
        public static final class Lifecycle extends SystemService {
            private final ActivityTaskManagerService mService;
    
            public Lifecycle(Context context) {
                // 这个context是SystemServiceManager传递过来的系统上下文, 
                // 即ContextImpl.getSystemContext()返回的实例
                super(context);
                //1.创建ActivityTaskManagerService对象
                mService = new ActivityTaskManagerService(context);
            }
    
            @Override
            public void onStart() {
                //有SystemService调用ServiceManager.addService()加入到servicemanager进程中管理
                publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
                //2.启动ATMS服务
                mService.start();
            }
    
            @Override
            public void onUnlockUser(int userId) {
                synchronized (mService.getGlobalLock()) {
                    mService.mStackSupervisor.onUserUnlocked(userId);
                }
            }
    
            @Override
            public void onCleanupUser(int userId) {
                synchronized (mService.getGlobalLock()) {
                    mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
                }
            }
    
            // 返回的是new的ActivityTaskManagerService实例,SystemSever中使用
            // SystemServiceManager.startService()后调用的getService()就是调用该方法
            public ActivityTaskManagerService getService() {
                return mService;
            }
        }
    

    2.1 创建ActivityTaskManagerService

      ActivityTaskManagerService简称ATMS,Android10新引入功能,用来管理Activity的启动、调度等功能。

      Android 10中把原先在AMS中activity的管理移动到ATMS中,从Android 10的代码路径可以看出,管理Activity的ATMS被放入到的wm路径中,这个路径原先归WindowManagerService控制,谷歌的目的也是希望在将来把activity和window融合在一起,减少冗余代码以及AMS和WMS的协调工作。

    • ATMS的路径为:frameworks/base/services/core/java/com/android/server/wm
    • AMS的路径为:frameworks/base/services/core/java/com/android/server/am
    // frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
    public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
        final Context mUiContext;
        final ActivityThread mSystemThread;
        final ActivityTaskManagerInternal mInternal;
    
        //ActivityStackSupervisor 是ATM中用来管理Activity启动和调度的核心类
        ActivityStackSupervisor mStackSupervisor;
        //Activity 容器的根节点
        RootWindowContainer mRootWindowContainer;
        //WMS 负责窗口的管理
        WindowManagerService mWindowManager;
    
        //这是我们目前认为是"Home" Activity的过程
        WindowProcessController mHomeProcess;
    
        public ActivityTaskManagerService(Context context) {
            //拿到System Context
            mContext = context;
            mFactoryTest = FactoryTest.getMode();
            //取出的是ActivityThread的静态变量sCurrentActivityThread
            //这意味着mSystemThread与SystemServer中的ActivityThread一致
            mSystemThread = ActivityThread.currentActivityThread();
            //拿到System UI Context
            mUiContext = mSystemThread.getSystemUiContext();
            mLifecycleManager = new ClientLifecycleManager();
            //拿到LocalService的对象
            mInternal = new LocalService();
            GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
            mWindowOrganizerController = new WindowOrganizerController(this);
            mTaskOrganizerController = mWindowOrganizerController.mTaskOrganizerController;
        }
    }
    

    在ActivityTaskManagerService的构造方法中初始化了ActivityThread实例,它的使用会在之后慢慢展开,此处给出ActivityThread的官方解释:它管理应用程序进程中主线程的执行、调度和执行activities、broadcasts和其他ActivityManagerService请求的其他操作。

    2.2 ActivityTaskManagerService.start()

      该方法在启动ActivityTaskManagerService时会被调用,在Lifecycle.onStart()中调用了该start()。

    // frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
        private void start() {
            LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
        }
    

    mInternal是创建的LocalService对象,它是ActivityTaskManagerService的内部类,继承了ActivityTaskManagerInternal的抽象类。这里的addService()方法会将ActivityTaskManagerInternal添加到本地服务的全局注册表中。

      Activity Task manager的本地系统服务接口,只能在system server进程中使用。它的接口定义如下:

    // frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerInternal.java
    public abstract class ActivityTaskManagerInternal {
        public interface ScreenObserver {
            void onAwakeStateChanged(boolean isAwake);
            void onKeyguardStateChanged(boolean isShowing);
        }  
        public abstract void registerScreenObserver(ScreenObserver observer); 
    
        public abstract ComponentName getHomeActivityForUser(int userId);
        public abstract int startActivitiesAsPackage(String packageName,
                int userId, Intent[] intents, Bundle bOptions);
    
        public abstract int startActivityAsUser(IApplicationThread caller, String callingPackage,
                Intent intent, @Nullable Bundle options, int userId);
        public abstract boolean isSleeping();
        public abstract boolean isShuttingDown();
        public abstract boolean shuttingDown(boolean booted, int timeout);
        public abstract void enableScreenAfterBoot(boolean booted);
    
         public final class ActivityTokens {
            private final @NonNull IBinder mActivityToken;
            private final @NonNull IBinder mAssistToken;
            private final @NonNull IApplicationThread mAppThread;
            ...
        }
    
        public abstract Intent getHomeIntent();
        public abstract boolean startHomeActivity(int userId, String reason);
        ...
    
    }
    

    3.ActivityManagerService启动过程

      SystemServer中startBootstrapServices()方法启动ATMS后,紧接就是去启动AMS。在Android 10的版本中,Activity的管理和调度移到ATMS中,AMS负责 service,broadcast,provider的管理和调度。

    // frameworks/base/services/java/com/android/server/SystemServer.java
    private void startBootstrapServices() {
        ...
        //启动AMS
        mActivityManagerService = ActivityManagerService.Lifecycle.startService(
                mSystemServiceManager, atm);
        ...
    }
    

    从《1.2.1 SystemServiceManager()》中,可以知道SystemServiceManager.startService()最终调用的是启动对象中的onStart方法,因此AMS启动,这里最终会调用ActivityTaskManagerService.Lifecycle.onStart()来启动AMS服务:

    // frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
        public static final class Lifecycle extends SystemService {
            private final ActivityManagerService mService;
            private static ActivityTaskManagerService sAtm;
    
            public Lifecycle(Context context) {
                super(context);
                //1.创建ActivityManagerService,得到对象,传入ATM的对象
                mService = new ActivityManagerService(context, sAtm);
            }
    
            public static ActivityManagerService startService(
                    SystemServiceManager ssm, ActivityTaskManagerService atm) {
                sAtm = atm;
                return ssm.startService(ActivityManagerService.Lifecycle.class).getService();
            }
    
            @Override
            public void onStart() {
                //2.启动AMS服务
                mService.start();
            }
    
            @Override
            public void onBootPhase(int phase) {
                mService.mBootPhase = phase;
                if (phase == PHASE_SYSTEM_SERVICES_READY) {
                    mService.mBatteryStatsService.systemServicesReady();
                    mService.mServices.systemServicesReady();
                } else if (phase == PHASE_ACTIVITY_MANAGER_READY) {
                    mService.startBroadcastObservers();
                } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
                    mService.mPackageWatchdog.onPackagesReady();
                }
            }
    
            @Override
            public void onCleanupUser(int userId) {
                mService.mBatteryStatsService.onCleanupUser(userId);
            }
    
            public ActivityManagerService getService() {
                return mService;
            }
        }
    

    3.1 创建ActivityManagerService

      Activity的管理和调度放入到ATMS中执行,AMS中保留service,broadcast,provider的管理和调度。构造函数初始化主要工作就是初始化一些变量,供之后的service,broadcast,provider的管理和调度。

    // frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
    public class ActivityManagerService extends IActivityManager.Stub
            implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
        ...
        public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
            LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
            mInjector = new Injector(systemContext);
            //系统上下文,由systemserver进程创建的,ContextImpl.getSystemContext()得到的
            mContext = systemContext;
    
            mFactoryTest = FactoryTest.getMode();
            //取出的是ActivityThread的静态变量sCurrentActivityThread
            //这意味着mSystemThread与SystemServer中的ActivityThread一致
            mSystemThread = ActivityThread.currentActivityThread();
            mUiContext = mSystemThread.getSystemUiContext();
    
            Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
    
            //mHandler和mUiHandler初始化
            mHandlerThread = new ServiceThread(TAG,
                    THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
            mHandlerThread.start();
            //处理AMS中消息的主力
            mHandler = new MainHandler(mHandlerThread.getLooper());
            //UiHandler对应于Android中的UiThreads
            mUiHandler = mInjector.getUiHandler(this);
    
            //mProcStartHandler初始化
            mProcStartHandlerThread = new ServiceThread(TAG + ":procStart",
                    THREAD_PRIORITY_FOREGROUND, false /* allowIo */);
            mProcStartHandlerThread.start();
            mProcStartHandler = new Handler(mProcStartHandlerThread.getLooper());
            ...
            //创建 BroadcastQueue 前台广播对象,处理超时时长是 10s
            mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
                    "foreground", foreConstants, false);
            //创建 BroadcastQueue 后台广播对象,处理超时时长是 60s
            mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
                    "background", backConstants, true);
            //创建 BroadcastQueue 分流广播对象,处理超时时长是 60s
            mOffloadBroadcastQueue = new BroadcastQueue(this, mHandler,
                    "offload", offloadConstants, true);
            mBroadcastQueues[0] = mFgBroadcastQueue;
            mBroadcastQueues[1] = mBgBroadcastQueue;
            mBroadcastQueues[2] = mOffloadBroadcastQueue;
    
            // 创建 ActiveServices 对象,用于管理 ServiceRecord 对象
            mServices = new ActiveServices(this);
            mProviderMap = new ProviderMap(this);
            mPackageWatchdog = PackageWatchdog.getInstance(mUiContext);
            mAppErrors = new AppErrors(mUiContext, this, mPackageWatchdog);
    
            final File systemDir = SystemServiceManager.ensureSystemDir();
    
            // TODO: Move creation of battery stats service outside of activity manager service.
            //初始化BatteryStatsService
            mBatteryStatsService = new BatteryStatsService(systemContext, systemDir,
                    BackgroundThread.get().getHandler());
            mBatteryStatsService.getActiveStatistics().readLocked();
            mBatteryStatsService.scheduleWriteToDisk();
            mOnBattery = DEBUG_POWER ? true
                    : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
            mBatteryStatsService.getActiveStatistics().setCallback(this);
            ...
            mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
            mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
    
            //持有atm引用,并调用其initialize()
            mActivityTaskManager = atm;
            mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController,
                    DisplayThread.get().getLooper());
            //获取其local service对象
            mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);
            ...
            //加入Watchdog的监控
            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);
        }
    

    3.2 ActivityManagerService.start()

      该方法主要工作有:

    1. 启动CPU监控线程,在启动CPU监控线程之前,首先将进程复位;
    2. 注册电池状态服务和权限管理服务。
    // frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
        private void start() {
            //1.移除所有的进程组
            removeAllProcessGroups();
            //启动 CPU 监控线程
            mProcessCpuThread.start();
    
            //2.注册电池状态和权限管理服务
            mBatteryStatsService.publish();
            mAppOpsService.publish();
            Slog.d("AppOps", "AppOpsService published");
            LocalServices.addService(ActivityManagerInternal.class, mInternal);
            mActivityTaskManager.onActivityManagerInternalAdded();
            mPendingIntentController.onActivityManagerInternalAdded();
            // Wait for the synchronized block started in mProcessCpuThread,
            // so that any other access to mProcessCpuTracker from main thread
            // will be blocked during mProcessCpuTracker initialization.
            try {
                mProcessCpuInitLatch.await();
            } catch (InterruptedException e) {
                Slog.wtf(TAG, "Interrupted wait during start", e);
                Thread.currentThread().interrupt();
                throw new IllegalStateException("Interrupted wait during start");
            }
        }
    

    4.AMS设置SystemServiceManager和Installer

      继续回到《1.3 启动核心服务》中,在启动完ATMS和AMS后,会去设置SystemServiceManager和Installer:

    // frameworks/base/services/java/com/android/server/SystemServer.java
        private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
            ...
            //3.把ssm和installer赋值给ActivityManagerService
            mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
            mActivityManagerService.setInstaller(installer);
            ...
        }
    

    这里回去调用AMS中对应的方法:

    // frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
    public class ActivityManagerService extends IActivityManager.Stub
            implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback, ActivityManagerGlobalLock {   
        ...
        public void setSystemServiceManager(SystemServiceManager mgr) {
            mSystemServiceManager = mgr;
        }
    
        public void setInstaller(Installer installer) {
            mInstaller = installer;
        }
        ...
    }
    

    这里只是简单地将两个对象保存到AMS中,后续会用到。

    5.获取ATMS的全局Lock

      继续回到《1.3 启动核心服务》中:

    // frameworks/base/services/java/com/android/server/SystemServer.java
        private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
            ...
            //4\. 利用atm,获取WindowManagerGlobalLock
            mWindowManagerGlobalLock = atm.getGlobalLock();
            ...
        }
    

    继续调用ATMS中的方法:

    // frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
    public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
        final WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
        ...
        public WindowManagerGlobalLock getGlobalLock() {
            return mGlobalLock;
        }
    }
    ----------------
    // frameworks/base/services/core/java/com/android/server/wm/WindowManagerGlobalLock.java
    public class WindowManagerGlobalLock {
    }
    

    6.AMS.initPowerManagement()

      继续回到《1.3 启动核心服务》中:

    // frameworks/base/services/java/com/android/server/SystemServer.java
        private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
            ...
            //5.初始化PowerManager
            mActivityManagerService.initPowerManagement();
            ...
        }
    

    调用AMS中的方法:

    // frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
    public class ActivityManagerService extends IActivityManager.Stub
            implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback, ActivityManagerGlobalLock { 
        ...
        public void initPowerManagement() {
            mActivityTaskManager.onInitPowerManagement();
            mBatteryStatsService.initPowerManagement();
            // AMS持有PowerMManagerInternal service引用
            mLocalPowerManager = LocalServices.getService(PowerManagerInternal.class);
        }
        ...
    }
    

    ATMS同AMS一样,也持有PowerManagerInternal service引用,ATMS.onInitPowerManagement()如下:

    // /frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
    public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
        public void onInitPowerManagement() {
            synchronized (mGlobalLock) {
                mTaskSupervisor.initPowerManagement();
                final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
                //持有PowerManagerInternal service引用
                mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
                mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
                mVoiceWakeLock.setReferenceCounted(false);
            }
        }
        ...
    }
    

    继续initPowerManagement()方法:

    // /frameworks/base/services/core/java/com/android/server/am/BatteryStatsService.java
    public final class BatteryStatsService extends IBatteryStats.Stub
            implements PowerManagerInternal.LowPowerModeListener,
            BatteryStatsImpl.PlatformIdleStateCallback,
            BatteryStatsImpl.MeasuredEnergyRetriever,
            Watchdog.Monitor {
    
        public void initPowerManagement() {
            //持有PowerManagerInternal service引用,并注册低电量模式监听
            final PowerManagerInternal powerMgr = LocalServices.getService(PowerManagerInternal.class);
            powerMgr.registerLowPowerModeObserver(this);
            synchronized (mStats) {
                mStats.notePowerSaveModeLocked(
                        powerMgr.getLowPowerState(ServiceType.BATTERY_STATS).batterySaverEnabled,
                        SystemClock.elapsedRealtime(), SystemClock.uptimeMillis(), true);
            }
            (new WakeupReasonThread()).start();
     }   
    

    7.AMS.setSystemProcess()

      继续回到《1.3 启动核心服务》中:

    // frameworks/base/services/java/com/android/server/SystemServer.java
        private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
            ...
            //6.设置系统进程
            mActivityManagerService.setSystemProcess();
            ...
        }
    

    该方法主要业务:

    1. 把AMS作为name = activity添加到systemserver进程中管理;
    2. 注册procstats服务(进程状态),meminfo服务(内存信息),gfxinfo服务(图像信息),dbinfo服务(数据库信息),cpuinfo服务(cup信息),permission服务(权限控制信息),processinfo服务(进程信息),cacheinfo服务(cache信息)注册到systemserver进程中进行管理;
    3. 获取package=“android”的ApplicationInfo,为ActivityThread安装相关system application信息;
    4. 为systemserver 主进程开辟一个ProcessRecord来维护进程的相关信息。
    // frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
        public void setSystemProcess() {
            try {
                //1.注册一些服务到ServiceManager:
                //包括 activity、procstats、meminfo、gfxinfo、dbinfo、permission、processinfo
                //把AMS注册到systemserver进程中管理:activity
                ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
                        DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
                //注册进程状态服务:procstats
                ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
                //注册内存信息服务:meminfo
                ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false,
                        DUMP_FLAG_PRIORITY_HIGH);
                //注册图像信息服务和数据库信息服务:gfxinfo,dbinfo
                ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
                ServiceManager.addService("dbinfo", new DbBinder(this));
                if (MONITOR_CPU_USAGE) {
                    //注册cupinfo服务到systemserver进程中,CUP信息
                    ServiceManager.addService("cpuinfo", new CpuBinder(this),
                            /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
                }
                //注册权限服务、进程信息服务、缓存信息服务:permission,processinfo,cacheinfo
                ServiceManager.addService("permission", new PermissionController(this));
                ServiceManager.addService("processinfo", new ProcessInfoService(this));
                ServiceManager.addService("cacheinfo", new CacheBinder(this));
    
                //2.通过解析framework-res.apk里的AndroidManifest.xml获得ApplicationInfo
                ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
                        "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
                //3.为ActivityThread 安装 system application相关信息,
                //将framework-res.apk对应的ApplicationInfo安装到LoadedApk中的mApplicationInfo
                mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
    
                //4.为systemserver主进程开辟一个ProcessRecord来维护进程的相关信息
                synchronized (this) {
                    ProcessRecord app = mProcessList.newProcessRecordLocked(info, info.processName,
                            false,
                            0,
                            new HostingRecord("system"));
                    app.setPersistent(true);//设置进程常驻
                    app.pid = MY_PID;//为ProcessRecord赋值当前进程ID,即system_server进程ID
                    app.getWindowProcessController().setPid(MY_PID);
                    app.maxAdj = ProcessList.SYSTEM_ADJ;
                    app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
                    addPidLocked(app);//将ProcessRecord放到mPidSelfLocked里统一管理
                    mProcessList.updateLruProcessLocked(app, false, null);
                    updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
                }
            } 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.
            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 (getAppOpsManager().checkOpNoThrow(op, uid, packageName)
                                        != AppOpsManager.MODE_ALLOWED) {
                                    runInBackgroundDisabled(uid);
                                }
                            }
                        }
                    });
    
            final int[] cameraOp = {AppOpsManager.OP_CAMERA};
            mAppOpsService.startWatchingActive(cameraOp, new IAppOpsActiveCallback.Stub() {
                @Override
                public void opActiveChanged(int op, int uid, String packageName, boolean active) {
                    cameraActiveChanged(uid, active);
                }
            });
        }
    

    7.1 getApplicationInfo()

      这里会通过PackageManagerService.java的getApplicationInfo()方法去获取Application的信息:

                //2.通过解析framework-res.apk里的AndroidManifest.xml获得ApplicationInfo
                ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
                        "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
    

    获取package="android"的ApplicationInfo,为ActivityThread安装相关system application信息;在后边的章节中介绍了AMS的这个mSystemThread,这个实际上是systemserver进程的主线程,所以此处是在systemserver进程中安装了framework-res.apk,(之后系统还会安装SettingsProvider.apk)。

      此处安装的是framework-res.apk。因为只有该apk的AndroidManifest.xml中package="android"且是SYSTEM_UID,如下:

    // frameworks/base/core/res/AndroidManifest.xml
    
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="android" coreApp="true" android:sharedUserId="android.uid.system"
        android:sharedUserLabel="@string/android_system_label">
    
        <!-- ================================================ -->
        <!-- Special broadcasts that only the system can send -->
        <!-- ================================================ -->
        <eat-comment />
    

    7.2 installSystemApplicationInfo()

      这里会通过ActivityThread.java的installSystemApplicationInfo()方法安装system application的信息:

                //3.为ActivityThread安装 system application相关信息,
                //将framework-res.apk对应的ApplicationInfo安装到LoadedApk中的mApplicationInfo
                mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
    

    继续调用ActivityThread.java中的方法:

    // frameworks/base/core/java/android/app/ActivityThread.java
        public void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) {
            synchronized (this) {
                getSystemContext().installSystemApplicationInfo(info, classLoader);
                getSystemUiContext().installSystemApplicationInfo(info, classLoader);
    
                // give ourselves a default profiler
                mProfiler = new Profiler();
            }
        }
    

    8.AMS.systemReady()

      经过上面的分析,已经梳理出了AMS和ATMS的启动过程。这里再回到《1.SystemServer启动》中,在SystemServer的run()方法中,在调用startBootstrapServices()启动完AMS和ATMS服务后,会在startOtherServices()中启动完其他的服务之后,调用AMS的systemReady()方法去作一些准备工作。

      AMS的systemReady处理分为三个阶段:

    • 阶段1:主要是调用一些关键服务的初始化函数, 然后杀死那些没有FLAG_PERSISTENT却在AMS启动完成前已经存在的进程, 同时获取一些配置参数。 需要注意的是,由于只有Java进程才会向AMS注册,而一般的Native进程不会向AMS注册,因此此处杀死的进程是Java进程。

    • 阶段2:执行goingCallback的处理,主要的工作就是通知一些服务可以进行systemReady、systemRunning相关的工作,并进行启动服务或应用进程的工作。

    • 阶段3:启动Home Activity,当启动结束,并发送ACTION_BOOT_COMPLETED广播时,AMS的启动过程告一段落。

    // frameworks/base/services/java/com/android/server/SystemServer.java
       private void startOtherServices() {
            mActivityManagerService.systemReady(() -> {xxxxxgoingCallbackxxx, BOOT_TIMINGS_TRACE_LOG);
        }
    
     // frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
        public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
            阶段1:关键服务的初始化
            阶段2:goingCallback处理
            阶段3:启动Home Activity,完成AMS启动
        }
    

    8.1 systemReady阶段1

      主要是调用一些关键服务的初始化函数, 然后杀死那些没有FLAG_PERSISTENT却在AMS启动完成前已经存在的进程, 同时获取一些配置参数。 需要注意的是,由于只有Java进程才会向AMS注册,而一般的Native进程不会向AMS注册,因此此处杀死的进程是Java进程。

    // frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
        public void systemReady(final Runnable goingCallback, @NonNull TimingsTraceAndSlog t) {
            t.traceBegin("PhaseActivityManagerReady");
            mSystemServiceManager.preSystemReady();
            synchronized(this) {
                //第一次进入mSystemReady 为false,不走该流程
                if (mSystemReady) {
                    // If we're done calling all the receivers, run the next "boot phase" passed in
                    // by the SystemServer
                    if (goingCallback != null) {
                        goingCallback.run();
                    }
                    t.traceEnd(); // PhaseActivityManagerReady
                    return;
                }
    
                t.traceBegin("controllersReady");
                mLocalDeviceIdleController =
                        LocalServices.getService(DeviceIdleInternal.class);
                //这一部分主要是调用一些关键服务SystemReady相关的函数,
                //进行一些等待AMS初始完,才能进行的工作
                mActivityTaskManager.onSystemReady();
                // Make sure we have the current profile info, since it is needed for security checks.
                mUserController.onSystemReady();
                mAppOpsService.systemReady();
                mProcessList.onSystemReady();
                mSystemReady = true;
                t.traceEnd();
            }
    
            try {
                sTheRealBuildSerial = IDeviceIdentifiersPolicyService.Stub.asInterface(
                        ServiceManager.getService(Context.DEVICE_IDENTIFIERS_SERVICE))
                        .getSerial();
            } catch (RemoteException e) {}
    
            t.traceBegin("killProcesses");
            ArrayList<ProcessRecord> procsToKill = null;
            synchronized(mPidsSelfLocked) {
                //mPidsSelfLocked中保存当前正在运行的所有进程的信息
                for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
                    ProcessRecord proc = mPidsSelfLocked.valueAt(i);
                    //在AMS启动完成前,如果没有FLAG_PERSISTENT标志的进程已经启动了,
                    //就将这个进程加入到procsToKill中
                    if (!isAllowedWhileBooting(proc.info)){
                        if (procsToKill == null) {
                            procsToKill = new ArrayList<ProcessRecord>();
                        }
                        procsToKill.add(proc);
                    }
                }
            }
    
            //收集已经启动的进程并杀死,排除persistent常驻进程
            synchronized(this) {
                //利用removeProcessLocked关闭procsToKill中的进程
                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);
                        mProcessList.removeProcessLocked(proc, true, false,
                                ApplicationExitInfo.REASON_OTHER,
                                ApplicationExitInfo.SUBREASON_SYSTEM_UPDATE_DONE,
                                "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;
            }
            ...
            mUgmInternal.onSystemReady();
            ...
            }
        }
    

    8.2 systemReady阶段2

      执行goingCallback的处理,主要的工作就是通知一些服务可以进行systemReady相关的工作,并进行启动服务或应用进程的工作。

    // frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
    public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
        ...
        //1.调用参数传入的runnable对象,SystemServer中有具体的定义,参考[4.7.2.1]
        if (goingCallback != null) goingCallback.run();
        ...
        //调用所有系统服务的onStartUser接口
        if (bootingSystemUser) {
            mSystemServiceManager.startUser(t, currentUserId);
        }
        synchronized (this) {
            //2.启动persistent为1的application所在的进程
            startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE);
            // Start up initial activity.
            mBooting = true;
            ...
    }
    

    8.2.1 goingCallback.run()

      监控Native的crash,启动WebView,执行一些服务的systemReady 和systemRunning方法。

    // frameworks/base/services/java/com/android/server/SystemServer.java
        private void startOtherServices(@NonNull TimingsTraceAndSlog t) {
            ...
            mActivityManagerService.systemReady(() -> {
                ...
    
                try {
                    //1.监控Native的crash
                    mActivityManagerService.startObservingNativeCrashes();
                } catch (Throwable e) {
                    reportWtf("observing native crashes", e);
                }
                t.traceEnd();
    
                // No dependency on Webview preparation in system server. But this should
                // be completed before allowing 3rd party
                final String WEBVIEW_PREPARATION = "WebViewFactoryPreparation";
                Future<?> webviewPrep = null;
                if (!mOnlyCore && mWebViewUpdateService != null) {
                    webviewPrep = SystemServerInitThreadPool.submit(() -> {
                        Slog.i(TAG, WEBVIEW_PREPARATION);
                        TimingsTraceAndSlog traceLog = TimingsTraceAndSlog.newAsyncLog();
                        traceLog.traceBegin(WEBVIEW_PREPARATION);
                        ConcurrentUtils.waitForFutureNoInterrupt(mZygotePreload, "Zygote preload");
                        mZygotePreload = null;
                        //2.启动WebView
                        mWebViewUpdateService.prepareWebViewInSystemServer();
                        traceLog.traceEnd();
                    }, WEBVIEW_PREPARATION);
                }
                ...
                try {
                    //3.启动systemUI
                    startSystemUi(context, windowManagerF);
                } catch (Throwable e) {
                    reportWtf("starting System UI", e);
                }
    
                //4.执行一系列服务的systemReady方法
                networkManagementF.systemReady();
                ipSecServiceF.systemReady();
                networkStatsF.systemReady();
                connectivityF.systemReady();
                networkPolicyF.systemReady(networkPolicyInitReadySignal);
                ...
                mSystemServiceManager.startBootPhase(t, SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
                ...
                //5.执行一系列服务的systemRunning方法
                locationF.systemRunning();
                countryDetectorF.systemRunning();
                networkTimeUpdaterF.systemRunning();
                inputManagerF.systemRunning();
                telephonyRegistryF.systemRunning();
                mediaRouterF.systemRunning();
                mmsServiceF.systemRunning();
                ...
        }
    

    这里继续看一下startSystemUi()方法,启动systemUI服务,服务名称”com.android.systemui/.SystemUIService”:

    // frameworks/base/services/java/com/android/server/SystemServer.java
        private static void startSystemUi(Context context, WindowManagerService windowManager) {
            PackageManagerInternal pm = LocalServices.getService(PackageManagerInternal.class);
            Intent intent = new Intent();
            intent.setComponent(pm.getSystemUiServiceComponent());//获取SystemUI的Component
            intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
            //Slog.d(TAG, "Starting service: " + intent);
            context.startServiceAsUser(intent, UserHandle.SYSTEM);//启动SystemUI服务
            windowManager.onSystemUiStarted();
        }
    

    8.2.2 AMS.startPersistentApps()

      该方法用于启动persistent为1的application所在的进程:

    // frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
        void startPersistentApps(int matchFlags) {
            if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) return;
    
            synchronized (this) {
                try {
                    //从PKMS中得到persistent为1的ApplicationInfo
                    final List<ApplicationInfo> apps = AppGlobals.getPackageManager()
                            .getPersistentApplications(STOCK_PM_FLAGS | matchFlags).getList();
                    for (ApplicationInfo app : apps) {
                        //由于framework-res.apk已经由系统启动,所以此处不再启动它
                        if (!"android".equals(app.packageName)) {
                            addAppLocked(app, null, false, null /* ABI override */,
                                    ZYGOTE_POLICY_FLAG_BATCH_LAUNCH);
                        }
                    }
                } catch (RemoteException ex) {
                }
            }
        }
    

    8.3 systemReady阶段3

      启动Home Activity,当启动结束,并发送ACTION_BOOT_COMPLETED广播时,AMS的启动过程告一段落。

    // frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
        public void systemReady(final Runnable goingCallback, @NonNull TimingsTraceAndSlog t) {
                ...
                if (bootingSystemUser) {
                    t.traceBegin("startHomeOnAllDisplays");
                    //1.通过ATM,启动Home Activity
                    mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");
                    t.traceEnd();
                }
                    ...
                    //2.发送一些广播消息
                    try {
                        //2.1 system发送广播 ACTION_USER_STARTED = "android.intent.action.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, null, intent,
                                null, null, 0, null, null, null, OP_NONE,
                                null, false, false, MY_PID, SYSTEM_UID, callingUid, callingPid,
                                currentUserId);
                        //2.2 system发送广播 ACTION_USER_STARTING= "android.intent.action.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, null, intent, null,
                                new IIntentReceiver.Stub() {
                                    @Override
                                    public void performReceive(Intent intent, int resultCode,
                                            String data, Bundle extras, boolean ordered, boolean sticky,
                                            int sendingUser) {}
                                }, 0, null, null, new String[] {INTERACT_ACROSS_USERS}, OP_NONE, null,
                                true, false, MY_PID, SYSTEM_UID, callingUid, callingPid,
                                UserHandle.USER_ALL);
                    } catch (Throwable e) {
                        Slog.wtf(TAG, "Failed sending first user broadcasts", e);
                    } finally {
                        Binder.restoreCallingIdentity(ident);
                ...
            }
        }
    

    8.3.1 ATMS.startHomeOnAllDisplays()

      该方法用于启动Home Activity:

    // frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
            public boolean startHomeOnAllDisplays(int userId, String reason) {
                synchronized (mGlobalLock) {
                    // 调用RootWindowContainer的startHomeOnAllDisplays(),最终到startHomeOnDisplay()
                    return mRootWindowContainer.startHomeOnAllDisplays(userId, reason);
                }
            }
    

    调用RootWindowContainer的startHomeOnAllDisplays()方法:

    // frameworks/base/services/core/java/com/android/server/wm/RootWindowContainer.java
        boolean startHomeOnAllDisplays(int userId, String reason) {
            boolean homeStarted = false;
            for (int i = getChildCount() - 1; i >= 0; i--) {
                final int displayId = getChildAt(i).mDisplayId;
                homeStarted |= startHomeOnDisplay(userId, reason, displayId);
            }
            return homeStarted;
        }
    
        boolean startHomeOnDisplay(int userId, String reason, int displayId) {
            return startHomeOnDisplay(userId, reason, displayId, false /* allowInstrumenting */,
                    false /* fromHomeKey */);
        }
    
        boolean startHomeOnDisplay(int userId, String reason, int displayId, boolean allowInstrumenting,
                boolean fromHomeKey) {
            // Fallback to top focused display or default display if the displayId is invalid.
            if (displayId == INVALID_DISPLAY) {
                final ActivityStack stack = getTopDisplayFocusedStack();
                displayId = stack != null ? stack.getDisplayId() : DEFAULT_DISPLAY;
            }
    
            final DisplayContent display = getDisplayContent(displayId);
            boolean result = false;
            for (int tcNdx = display.getTaskDisplayAreaCount() - 1; tcNdx >= 0; --tcNdx) {
                final TaskDisplayArea taskDisplayArea = display.getTaskDisplayAreaAt(tcNdx);
                result |= startHomeOnTaskDisplayArea(userId, reason, taskDisplayArea,
                        allowInstrumenting, fromHomeKey);
            }
            return result;
        }
    
        boolean startHomeOnTaskDisplayArea(int userId, String reason, TaskDisplayArea taskDisplayArea,
                boolean allowInstrumenting, boolean fromHomeKey) {
            // Fallback to top focused display area if the provided one is invalid.
            if (taskDisplayArea == null) {
                final ActivityStack stack = getTopDisplayFocusedStack();
                taskDisplayArea = stack != null ? stack.getDisplayArea()
                        : getDefaultTaskDisplayArea();
            }
    
            Intent homeIntent = null;
            ActivityInfo aInfo = null;
            if (taskDisplayArea == getDefaultTaskDisplayArea()) {
                homeIntent = mService.getHomeIntent();
                //根据intent中携带的ComponentName,利用PKMS得到ActivityInfo
                aInfo = resolveHomeActivity(userId, homeIntent);
            } else if (shouldPlaceSecondaryHomeOnDisplayArea(taskDisplayArea)) {
                Pair<ActivityInfo, Intent> info = resolveSecondaryHomeActivity(userId, taskDisplayArea);
                aInfo = info.first;
                homeIntent = info.second;
            }
            if (aInfo == null || homeIntent == null) {
                return false;
            }
    
            if (!canStartHomeOnDisplayArea(aInfo, taskDisplayArea, allowInstrumenting)) {
                return false;
            }
    
            // Updates the home component of the intent.
            homeIntent.setComponent(new ComponentName(aInfo.applicationInfo.packageName, aInfo.name));
            homeIntent.setFlags(homeIntent.getFlags() | FLAG_ACTIVITY_NEW_TASK);
            // Updates the extra information of the intent.
            if (fromHomeKey) {
                homeIntent.putExtra(WindowManagerPolicy.EXTRA_FROM_HOME_KEY, true);
                mWindowManager.cancelRecentsAnimation(REORDER_KEEP_IN_PLACE, "startHomeActivity");
            }
            // Update the reason for ANR debugging to verify if the user activity is the one that
            // actually launched.
            final String myReason = reason + ":" + userId + ":" + UserHandle.getUserId(
                    aInfo.applicationInfo.uid) + ":" + taskDisplayArea.getDisplayId();
            //启动Home Activity--Luncher
            mService.getActivityStartController().startHomeActivity(homeIntent, aInfo, myReason,
                    taskDisplayArea);
            return true;
        }
    

    这里的mService就是ActivityTaskManagerService,通过getActivityStartController()获取到ActivityStartController对象,然后再调用该对象的startHomeActivity()方法:

    // frameworks/base/services/core/java/com/android/server/wm/ActivityStartController.java
        void startHomeActivity(Intent intent, ActivityInfo aInfo, String reason,
                TaskDisplayArea taskDisplayArea) {
            final ActivityOptions options = ActivityOptions.makeBasic();
            options.setLaunchWindowingMode(WINDOWING_MODE_FULLSCREEN);
            if (!ActivityRecord.isResolverActivity(aInfo.name)) {
                // The resolver activity shouldn't be put in home stack because when the foreground is
                // standard type activity, the resolver activity should be put on the top of current
                // foreground instead of bring home stack to front.
                options.setLaunchActivityType(ACTIVITY_TYPE_HOME);
            }
            final int displayId = taskDisplayArea.getDisplayId();
            options.setLaunchDisplayId(displayId);
            options.setLaunchTaskDisplayArea(taskDisplayArea.mRemoteToken
                    .toWindowContainerToken());
    
            // The home activity will be started later, defer resuming to avoid unneccerary operations
            // (e.g. start home recursively) when creating home stack.
            mSupervisor.beginDeferResume();
            final ActivityStack homeStack;
            try {
                // Make sure home stack exists on display area.
                homeStack = taskDisplayArea.getOrCreateRootHomeTask(ON_TOP);
            } finally {
                mSupervisor.endDeferResume();
            }
    
            mLastHomeActivityStartResult = obtainStarter(intent, "startHomeActivity: " + reason)
                    .setOutActivity(tmpOutRecord)
                    .setCallingUid(0)
                    .setActivityInfo(aInfo)
                    .setActivityOptions(options.toBundle())
                    .execute();
            mLastHomeActivityStartRecord = tmpOutRecord[0];
            if (homeStack.mInResumeTopActivity) {
                // If we are in resume section already, home activity will be initialized, but not
                // resumed (to avoid recursive resume) and will stay that way until something pokes it
                // again. We need to schedule another resume.
                mSupervisor.scheduleResumeTopActivities();
            }
        }
    

    这里就分析到这,后面的详细分析后续另外单独分析。

      至此,AMS和ATMS的启动流程分析完毕。

    相关文章

      网友评论

          本文标题:Android ActivityManagerService--

          本文链接:https://www.haomeiwen.com/subject/ypwmvdtx.html