【framework】AMS启动流程

framework 专栏收录该内容
16 篇文章 5 订阅

1 前言

        AMS 即 ActivityManagerService,负责 Activy、Service、Broadcast、ContentProvider 四大组件的生命周期管理。本文主要介绍 AMS 的启动流程和初始化过程。AMS 在初始化的过程中,也伴随着了ATMS(ActivityTaskManagerService)的初始化。

        AMS 创建流程简述:

  • SystemServer:依次调用 main()、run()、startBootstrapServices(),再调用 Lifecyle 的 startService() 方法;
  • Lifecyle:startService() 方法中调用 SystemServiceManager 的 startService() 方法,并将 Lifecyle.class 传入;
  • SystemServiceManager:startService() 方法通过反射调用 Lifecyle 的构造方法,生成 Lifecyle 对象;
  • Lifecyle:构造方法中调用 AMS 的构造方法创建 AMS 对象,并通过 getService() 方法返回 AMS 对象。

2 AMS启动流程

        (1)main

        /frameworks/base/services/java/com/android/server/SystemServer.java

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

        (2)run

        /frameworks/base/services/java/com/android/server/SystemServer.java

private void run() {
	try {
		...
		// 创建Looper
		Looper.prepareMainLooper();
		// 加载libandroid_servers.so
		System.loadLibrary("android_servers");
		// 创建系统的 Context:ContextImpl.createSystemContext(new ActivityThread())
		createSystemContext();
		// 创建 SystemServiceManager
		mSystemServiceManager = new SystemServiceManager(mSystemContext);
		LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
		...
	}
	...
	try {
		//启动引导服务,ActivityManagerService、ActivityTaskManagerService、PackageManagerService、PowerManagerService、DisplayManagerService 等
		startBootstrapServices(); 
		//启动核心服务,BatteryService、UsageStatusService 等
		startCoreServices(); 
		//启动其他服务,InputManagerService、WindowManagerService、CameraService、AlarmManagerService 等
		startOtherServices(); 
		...
	}
	...
	// 开启消息循环
	Looper.loop();
}

        (3)startBootstrapServices

        /frameworks/base/services/java/com/android/server/SystemServer.java

private void startBootstrapServices() {
    ...
    Installer installer = mSystemServiceManager.startService(Installer.class);
	...
    //启动 ATMS
	ActivityTaskManagerService atm = mSystemServiceManager.startService(ActivityTaskManagerService.Lifecycle.class).getService();
    //启动 AMS,并注入 ATMS 
	mActivityManagerService = ActivityManagerService.Lifecycle.startService(mSystemServiceManager, atm);
    //注入 mSystemServiceManager 和 installer
    mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
    mActivityManagerService.setInstaller(installer);
	...
    //启动 PMS
    mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
    ...
    mActivityManagerService.initPowerManagement();
    ...
    mActivityManagerService.setSystemProcess();
    
}

        (4)AMS.Lifecycle

        /frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.Lifecycle.java

public static final class Lifecycle extends SystemService {
	private final ActivityManagerService mService;
	private static ActivityTaskManagerService sAtm;

	public Lifecycle(Context context) {//被 SystemServiceManager 的 startService() 方法调用
		super(context);
		mService = new ActivityManagerService(context, sAtm);
	}

	public static ActivityManagerService startService(SystemServiceManager ssm, ActivityTaskManagerService atm) {
		sAtm = atm;
		return ssm.startService(ActivityManagerService.Lifecycle.class).getService();
	}

    public void onStart() {
        mService.start(); //调用 AMS 的 start() 方法
    }

	...

    public ActivityManagerService getService() {
        return mService;
    }
}

        (5)startService

        /frameworks/base/services/core/java/com/android/server/SystemServiceManager.java

public <T extends SystemService> T startService(Class<T> serviceClass) {
	try {
		final String name = serviceClass.getName();
		...
		final T service;
		try { //通过反射调用 serviceClass 的构造方法 创建 Lifecycle 对象
			Constructor<T> constructor = serviceClass.getConstructor(Context.class);
			service = constructor.newInstance(mContext);
		}
		...
		startService(service);
		return service;
	}
	...
}

public void startService(SystemService service) {
	mServices.add(service); //mServices: ArrayList<SystemService>
	...
	try {
		service.onStart(); //调用 Lifecycle 的 onStart 方法
	}
	...
}

        注意:startService() 方法中调用了 Lifecycle 的 onStart() 方法,进一步调用 AMS 的 start() 方法初始化(下文还会介绍)。

3 AMS 初始化

        初始化过程如下: 

        (1)AMS 的构造方法

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

public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
	...
	mInjector = new Injector();
	mContext = systemContext;
	...
	mSystemThread = ActivityThread.currentActivityThread();
	mUiContext = mSystemThread.getSystemUiContext();
	...
	mHandlerThread = new ServiceThread(TAG, THREAD_PRIORITY_FOREGROUND, false);
	mHandlerThread.start();
	mHandler = new MainHandler(mHandlerThread.getLooper());
	mUiHandler = mInjector.getUiHandler(this);
	...
	mProcStartHandlerThread = new ServiceThread(TAG + ":procStart", THREAD_PRIORITY_FOREGROUND, false);
	mProcStartHandlerThread.start();
	mProcStartHandler = new Handler(mProcStartHandlerThread.getLooper());
	...
	final ActiveUids activeUids = new ActiveUids(this, true);
    mPlatformCompat = (PlatformCompat) ServiceManager.getService(Context.PLATFORM_COMPAT_SERVICE);
    mProcessList.init(this, activeUids, mPlatformCompat);
	...
	mServices = new ActiveServices(this); //用于启动 Service
	mProviderMap = new ProviderMap(this); //存储 ContentProvider
	...
	mUserController = new UserController(this);
	mPendingIntentController = new PendingIntentController(mHandlerThread.getLooper(), mUserController);
	...
	mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
	mActivityTaskManager = atm;
	//进一步初始化 ATMS
	mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController, DisplayThread.get().getLooper());
	mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);
	...
}

        (2)start

        start() 方法被 Lifecycle 的 onStart() 方法调用,onStart() 方法又被 SystemServiceManager 的 startService() 方法调用。

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

private void start() {
	...
	LocalServices.addService(ActivityManagerInternal.class, new LocalService());
	mActivityTaskManager.onActivityManagerInternalAdded();
	mUgmInternal.onActivityManagerInternalAdded();
	mPendingIntentController.onActivityManagerInternalAdded();
	...
}

        (3)initPowerManagement、setSystemProcess

        在 SystemServer 的 startBootstrapServices() 方法中,调用了 AMS 的 initPowerManagement() 和 setSystemProcess() 方法。

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

public void initPowerManagement() {
	mActivityTaskManager.onInitPowerManagement();
	mBatteryStatsService.initPowerManagement();
	mLocalPowerManager = LocalServices.getService(PowerManagerInternal.class);
}

public void setSystemProcess() {
	try {
		...
		synchronized (this) {
			ProcessRecord app = mProcessList.newProcessRecordLocked(info, info.processName, false, 0, new HostingRecord("system"));
			app.setPersistent(true);
			app.pid = MY_PID;
			app.getWindowProcessController().setPid(MY_PID);
			app.maxAdj = ProcessList.SYSTEM_ADJ;
			app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
			mPidsSelfLocked.put(app);
			mProcessList.updateLruProcessLocked(app, false, null);
			updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
		}
	}
	...
}

        (4)setUsageStatsManager

        在 SystemServer 的 startCoreServices() 方法中,调用了 AMS 的 setUsageStatsManager()  方法。

        /frameworks/base/services/java/com/android/server/SystemServer.java

private void startCoreServices() {
	...
	mSystemServiceManager.startService(UsageStatsService.class);
	mActivityManagerService.setUsageStatsManager(LocalServices.getService(UsageStatsManagerInternal.class));
	...
}

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

public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) {
	mUsageStatsService = usageStatsManager;
	mActivityTaskManager.setUsageStatsManager(usageStatsManager);
}

        (5)installSystemProviders、setWindowManager、systemReady

        在 SystemServer 的 startOtherServices() 方法中,调用了 AMS 的 installSystemProviders()、setWindowManager()  和 systemReady() 方法。

        /frameworks/base/services/java/com/android/server/SystemServer.java

private void startOtherServices() {
	...
	WindowManagerService wm = null;
	...
	try {
		...
		mActivityManagerService.installSystemProviders(); //1
		...
		wm = WindowManagerService.main(context, inputManager, !mFirstBoot, mOnlyCore, new PhoneWindowManager(), mActivityManagerService.mActivityTaskManager);
		...
		mActivityManagerService.setWindowManager(wm); //2
		...
	}
	...
	mActivityManagerService.systemReady(() -> { //3
		...
		mSystemServiceManager.startBootPhase(SystemService.PHASE_ACTIVITY_MANAGER_READY);
		...
		try {
			mActivityManagerService.startObservingNativeCrashes();
		}
		...
		try {
			startSystemUi(context, windowManagerF);
		}
		...
		mSystemServiceManager.startBootPhase(SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
		...
	}, BOOT_TIMINGS_TRACE_LOG);
}

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

public final void installSystemProviders() {
	List<ProviderInfo> providers;
	synchronized (this) {
		ProcessRecord app = mProcessList.mProcessNames.get("system", SYSTEM_UID);
		providers = generateApplicationProvidersLocked(app);
		...
	}
	if (providers != null) {
		mSystemThread.installSystemProviders(providers);
	}
	...
	mConstants.start(mContext.getContentResolver());
	mCoreSettingsObserver = new CoreSettingsObserver(this);
	mActivityTaskManager.installSystemProviders();
	...
}

public void setWindowManager(WindowManagerService wm) {
	synchronized (this) {
		mWindowManager = wm;
		mActivityTaskManager.setWindowManager(wm);
	}
}

public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
    //添加 AMS 服务,方便跨进程调用
    ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true, DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
	...
	synchronized(this) {
		...
		mLocalDeviceIdleController = LocalServices.getService(DeviceIdleController.LocalService.class);
		mActivityTaskManager.onSystemReady();
		mUserController.onSystemReady();
		mAppOpsService.systemReady();
		mSystemReady = true;
	}
	...
}

        已通过 ServiceManager.addService() 将 Context.ACTIVITY_SERVICE 与 AMS 绑定,因此在其他进程中可以通过如下方式获取 AMS。

IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
IActivityManager am = IActivityManager.Stub.asInterface(b);

  • 1
    点赞
  • 1
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值