前言

和WindowManagerService服务一样,ActivityManagerService也是Android系统中非常重要的服务,这个服务主要负责Android中四大组件的启动、通信、部分生命周期的管理等等。通常,为了方便书写,我们习惯将ActivityManagerService简写为AMS。在具体讲述和AMS相关的功能之前,我们需要先梳理一下ActivityManagerService的启动流程,这样才能更好的理解这个服务。

一、SystemServer启动ActivityManagerService服务

1、系统启动后会启动JVM虚拟机,SystemServer 是虚拟机的第一个进程,由init 进程fork 产生。主要用来启动frameworks层中的服务。SystemServer进程里面有个main()方法,main 方法如下:

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

2、main 方法里启动了 run() 方法,而在 run 方法中调用了startOtherServices() 方法:

public final class SystemServer {
   private void run() {
    	...代码省略...
        try {
            t.traceBegin("StartServices");
            startBootstrapServices(t);//引导服务
            startCoreServices(t);//核心服务
            startOtherServices(t);//其他服务
        } catch (Throwable ex) {
            Slog.e("System", "******************************************");
            Slog.e("System", "************ Failure starting system services", ex);
            throw ex;
        } finally {
            t.traceEnd(); // StartServices
        }
    	...代码省略...
    }
}

3、startBootstrapServices方法和ActivityManagerService服务启动相关的代码如下所示。

public final class SystemServer {

    private SystemServiceManager mSystemServiceManager;
    private ActivityManagerService mActivityManagerService;
    private WindowManagerGlobalLock mWindowManagerGlobalLock;

    private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
        ...代码省略...
        // Activity manager runs the show.
        t.traceBegin("StartActivityManager");
        //SystemServiceManager启动ActivityTaskManagerService服务
        ActivityTaskManagerService atm = mSystemServiceManager.startService(
                ActivityTaskManagerService.Lifecycle.class).getService();
        //调用ActivityManagerService.Lifecycle的静态方法startService启动ActivityManagerService服务
        mActivityManagerService = ActivityManagerService.Lifecycle.startService(
                mSystemServiceManager, atm);
        //ActivityManagerService持有SystemServiceManager的引用
        mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
        mActivityManagerService.setInstaller(installer);
        mWindowManagerGlobalLock = atm.getGlobalLock();
        t.traceEnd();
        ...代码省略...
    }
}

二、SystemServiceManager启动ActivityTaskManagerService服务

1、SystemServiceManager的startService方法如下所示。

public final class SystemServiceManager implements Dumpable {
    /**
     * 创建一个系统服务,该服务必须是com.android.server.SystemService的子类
     *
     * @param serviceClass 一个实现了SystemService接口的Java类
     * @return 返回一个服务实例对象
     */
    public <T extends SystemService> T startService(Class<T> serviceClass) {
        try {
            final String name = serviceClass.getName();
            Slog.i(TAG, "Starting " + name);
            Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartService " + name);

            // Create the service.
            if (!SystemService.class.isAssignableFrom(serviceClass)) {
                throw new RuntimeException("Failed to create " + name
                        + ": service must extend " + SystemService.class.getName());
            }
            final T service;
            try {
                //获取参数为Context的构造方法,通过反射创建service对象
                Constructor<T> constructor = serviceClass.getConstructor(Context.class);
                service = constructor.newInstance(mContext);
            } catch (InstantiationException ex) {
                throw new RuntimeException("Failed to create service " + name
                        + ": service could not be instantiated", ex);
            } catch (IllegalAccessException ex) {
                throw new RuntimeException("Failed to create service " + name
                        + ": service must have a public constructor with a Context argument", ex);
            } catch (NoSuchMethodException ex) {
                throw new RuntimeException("Failed to create service " + name
                        + ": service must have a public constructor with a Context argument", ex);
            } catch (InvocationTargetException ex) {
                throw new RuntimeException("Failed to create service " + name
                        + ": service constructor threw an exception", ex);
            }
            //继续调用startService方法
            startService(service);
            return service;
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
        }
    }
}

SystemServiceManager的startService首先会获取要启动的服务对象中带有Context参数的构造方法 ,并调用该构造方法创建服务实例对象,这里其实就是调用ActivityTaskManagerService.Lifecycle类中带有Context参数的构造方法,创建ActivityTaskManagerService.Lifecycle实例对象。

2、ActivityTaskManagerService.Lifecycle的的构造方法如下所示。

public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
    public static final class Lifecycle extends SystemService {
        private final ActivityTaskManagerService mService;

        public Lifecycle(Context context) {
            super(context);
            //创建ActivityTaskManagerService实例对象
            mService = new ActivityTaskManagerService(context);
        }
    }
}

在ActivityTaskManagerService.Lifecycle的构造方法中会创建ActivityTaskManagerService实例对象。

3、重新回到第1步,SystemServiceManager的startService(Class serviceClass) 方法通过反射创建ActivityTaskManagerService.Lifecycle实例对象之后,会继续调用自己的startService(@NonNull final SystemService service)方法。

public final class SystemServiceManager implements Dumpable {
    public void startService(@NonNull final SystemService service) {
        //在类型为ArrayList<SystemService>的属性集合mServices中注册新创建的服务对象
        mServices.add(service);
        //调用服务的onStart方法,开启服务
        long time = SystemClock.elapsedRealtime();
        try {
            service.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");
    }

通过以上代码可知,此方法首先在类型为ArrayList的属性集合mServices中注册新创建的ActivityTaskManagerService.Lifecycle实例对象,然后调用该实例对象的onStart方法。

4、这里一并贴出ActivityTaskManagerService.Lifecycle类的所有代码。

public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
    public static final class Lifecycle extends SystemService {
        private final ActivityTaskManagerService mService;

        public Lifecycle(Context context) {
            super(context);
            //创建ActivityTaskManagerService实例对象
            mService = new ActivityTaskManagerService(context);
        }

        @Override
        public void onStart() {
            //调用自己的父类SystemService的publishBinderService方法,
            //将ActivityTaskManagerService实例对象绑定到ServiceManager中
            publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
            mService.start();
        }

        @Override
        public void onUserUnlocked(@NonNull TargetUser user) {
            synchronized (mService.getGlobalLock()) {
                mService.mTaskSupervisor.onUserUnlocked(user.getUserIdentifier());
            }
        }

        @Override
        public void onUserStopped(@NonNull TargetUser user) {
            synchronized (mService.getGlobalLock()) {
                mService.mTaskSupervisor.mLaunchParamsPersister
                        .onCleanupUser(user.getUserIdentifier());
            }
        }

        public ActivityTaskManagerService getService() {
            return mService;
        }
    }
}

ActivityTaskManagerService.Lifecycle的onStart方法首先会调用自己的父类SystemService的publishBinderService方法,将ActivityTaskManagerService实例对象绑定到ServiceManager中。

三、ActivityManagerService.Lifecycle启动ActivityManagerService服务

1、重新回到第一节的第3步的startBootstrapServices方法中,在ActivityManagerService.Lifecycle实例对象被创建之后,系统会继续调用ActivityManagerService.Lifecycle的静态方法startService启动ActivityManagerService服务。

public class ActivityManagerService extends IActivityManager.Stub
        implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback, ActivityManagerGlobalLock {
    public static final class Lifecycle extends SystemService {
        private final ActivityManagerService mService;
        private static ActivityTaskManagerService sAtm;

        public Lifecycle(Context context) {
            super(context);
            mService = new ActivityManagerService(context, sAtm);
        }

        public static ActivityManagerService startService(SystemServiceManager ssm, ActivityTaskManagerService atm) {
            sAtm = atm;
            //和ActivityTaskManagerService服务的启动相似,也是调用SystemServiceManager的startService方法。
            return ssm.startService(ActivityManagerService.Lifecycle.class).getService();
        }

        @Override
        public void onStart() {
        	//调用AMS的start方法
            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 onUserStopped(@NonNull TargetUser user) {
            mService.mBatteryStatsService.onCleanupUser(user.getUserIdentifier());
        }

        public ActivityManagerService getService() {
            return mService;
        }
    }
}

ActivityManagerService.Lifecycle的startService内部也是调用SystemServiceManager的startService方法来启动ActivityManagerService服务的,过程和ActivityTaskManagerService的创建过程基本一致,最终也会触发ActivityManagerService.Lifecycle对象的构造方法,在该构造方法中创建ActivityManagerService实例对象,然后调用ActivityManagerService.Lifecycle对象的onStart方法,触发ActivityManagerService的start方法。

四、ActivityManagerService类定义

4.1 构造方法

public class ActivityManagerService extends IActivityManager.Stub
        implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback, ActivityManagerGlobalLock {

    // Note: This method is invoked on the main thread but may need to attach various
    // handlers to other threads.  So take care to be explicit about the looper.
    public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
        LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
        mInjector = new Injector(systemContext);
        mContext = systemContext;

        mFactoryTest = FactoryTest.getMode();
        mSystemThread = ActivityThread.currentActivityThread();
        mUiContext = mSystemThread.getSystemUiContext();

        Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());

        mHandlerThread = new ServiceThread(TAG,
                THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
        mHandlerThread.start();
        mHandler = new MainHandler(mHandlerThread.getLooper());
        mUiHandler = mInjector.getUiHandler(this);

        mProcStartHandlerThread = new ServiceThread(TAG + ":procStart",
                THREAD_PRIORITY_FOREGROUND, false /* allowIo */);
        mProcStartHandlerThread.start();
        mProcStartHandler = new Handler(mProcStartHandlerThread.getLooper());

        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);
        mOffloadBroadcastQueue = new BroadcastQueue(this, mHandler,
                "offload", offloadConstants, true);
        mBroadcastQueues[0] = mFgBroadcastQueue;
        mBroadcastQueues[1] = mBgBroadcastQueue;
        mBroadcastQueues[2] = mOffloadBroadcastQueue;

        mServices = new ActiveServices(this);
        mCpHelper = new ContentProviderHelper(this, true);
        mPackageWatchdog = PackageWatchdog.getInstance(mUiContext);
        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);

        mActivityTaskManager = atm;
        mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController,
                DisplayThread.get().getLooper());
        mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);

        mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext);

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

4.2 启动方法start代码如下。

public class ActivityManagerService extends IActivityManager.Stub
        implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback, ActivityManagerGlobalLock {
        
     private void start() {
        removeAllProcessGroups();
        mBatteryStatsService.publish();
        mAppOpsService.publish();
        Slog.d("AppOps", "AppOpsService published");
        LocalServices.addService(ActivityManagerInternal.class, mInternal);
        LocalManagerRegistry.addManager(ActivityManagerLocal.class,
                (ActivityManagerLocal) mInternal);
        mActivityTaskManager.onActivityManagerInternalAdded();
        mPendingIntentController.onActivityManagerInternalAdded();
        mAppProfiler.onActivityManagerInternalAdded();
    }
}
06-08 03:43