快捷搜索:  as  test  1111  xxx

Android 8.0 ActivityManagerService 启动流程

ActivityManagerService(以下简称为 AMS)是 Android 中最核心的系统办事之一,我觉得 AMS 最紧张的功能有两个:

对利用法度榜样进程的治理:利用法度榜样进程的创建、销毁和优先级的调剂

对利用法度榜样进程中的四大年夜组件进行治理:最常见的 Activity、Service 等四大年夜组件的生命周期措施都是经由过程 AMS 间接地调整履行的

这篇文章对 Android 8.0 系统中的 AMS 启动流程加以阐发。

一. 整体布局

首先,我们来看一下 AMS 中治理利用法度榜样进程和利用法度榜样进程中四大年夜组件的相关类和他们的关系图

AMS.png

图片滥觞:Android7.1 ActivityManagerService概述

ActivityThread 是利用法度榜样进程的进口,认真对利用法度榜样进程中主线程的治理,被 AMS 调整从而直接调用四大年夜组件的生命周期措施

在 AMS 中并不能直接治理四大年夜组件,四大年夜组件在 AMS 中都有一个对应的类,AMS 中治理的是 ActivityRecord 等工具,再经由过程 Binder 通信向 ApplicationThread 发送消息,ApplicationThread 再经由过程 Handler 将消息发送到主线程中,着末就会去调用四大年夜组件的生命周期措施

利用法度榜样进程中的四大年夜组件

AMS 中的四大年夜组件

Activity

ActivityRecord

Service

ServiceRecord

Broadcast

BroadcastRecord

ContentProvider

ContentProviderRecord

接下来,我们阐发下 AMS 的启动流程

二. SystemServer 的启动

和之前阐发 WMS 的启动一样,从 SystemServer 中开始阐发。

2.1 SystemServer 初始化

public final class SystemServer {

/**

* The main entry point from zygote.

*/

public static void main(String[] args) {

new SystemServer().run();

}

private void run() {

......

// 初始化虚拟机内存

VMRuntime.getRuntime().clearGrowthLimit();

VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);

//设置进程优先级,初始化 MainLooper

android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_FOREGROUND);

android.os.Process.setCanSelfBackground(false);

Looper.prepareMainLooper();

// 加载 native services

System.loadLibrary("android_servers");

......

// 代码 1,初始化 System Context

createSystemContext();

// 代码 2,创建 SystemServiceManager 工具

mSystemServiceManager = new SystemServiceManager(mSystemContext);

mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);

LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);

// 为初始化义务筹备线程池

SystemServerInitThreadPool.get();

// 代码 3,启动系统办事

try {

traceBeginAndSlog("StartServices");

startBootstrapServices();

startCoreServices();

startOtherServices();

SystemServerInitThreadPool.shutdown();

} catch (Throwable ex) {

Slog.e("System", "奸淫奸淫奸淫奸淫奸淫奸淫奸淫奸淫奸淫奸淫奸淫奸淫奸淫奸淫");

Slog.e("System", "奸淫奸淫奸淫奸淫 Failure starting system services", ex);

throw ex;

} finally {

traceEnd();

}

......

Looper.loop();

}

}

从上面代码中可以看到,在 SystemServer 中也持有 Context 工具,这个 Context 真是无处不在。SystemServer 初始化历程中,我们主要阐发三点:

代码 1 处初始化 SystemContext

代码 2 处创建 SystemServiceManager 工具

代码 3 处启动系统办事,共分为三种系统办事:系统向导办事(BootstrapServices)、核心办事(CoreServices)和其他办事(OtherServices)

2.2 初始化 SystemContext

首先来到 createSystemContext() 措施中,代码如下所示

private void createSystemContext() {

ActivityThread activityThread = ActivityThread.systemMain();

mSystemContext = activityThread.getSystemContext();

mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);

final Context systemUiContext = activityThread.getSystemUiContext();

systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);

}

在 createSystemContext() 中调用 ActivityThread.systemMain() 创建了一个 ActivityThread 工具,并设置了此 ActivityThread 工具 SystemContext 和 SystemUIContext 的主题,接着我们看下 ActivityThread.systemMain() 措施

public final class ActivityThread {

......

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

}

ActivityThread thread = new ActivityThread();

thread.attach(true);

return thread;

}

......

private void attach(boolean system) {

sCurrentActivityThread = this;

mSystemThread = system;

if (!system) {

// 非系统启动

......

} else {

// 经由过程 SystemServer 启动 ActivityThread 工具

android.ddm.DdmHandleAppName.setAppName("system_process",

UserHandle.myUserId());

try {

// 代码 1,创建 Instrumentation、Application、Context 工具

mInstrumentation = new Instrumentation();

ContextImpl context = ContextImpl.createAppContext(

this, getSystemContext().mPackageInfo);

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

mInitialApplication.onCreate();

} catch (Exception e) {

throw new RuntimeException(

"Unable to instantiate Application():" + e.toString(), e);

}

}

// 为 ViewRootImpl 设置设置设置设备摆设摆设更新回调,当系统资本设置设置设备摆设摆设(如:系统字体)发生变更时,看护系统设置设置设备摆设摆设发生变更

ViewRootImpl.ConfigChangedCallback configChangedCallback

= (Configuration globalConfig) -> {

synchronized (mResourcesManager) {

// We need to apply this change to the resources immediately, because upon returning

// the view hierarchy will be informed about it.

if (mResourcesManager.applyConfigurationToResourcesLocked(globalConfig,

null /* compat */)) {

updateLocaleListFromAppContext(mInitialApplication.getApplicationContext(),

mResourcesManager.getConfiguration().getLocales());

// This actually changed the resources! Tell everyone about it.

if (mPendingConfiguration == null

|| mPendingConfiguration.isOtherSeqNewer(globalConfig)) {

mPendingConfiguration = globalConfig;

sendMessage(H.CONFIGURATION_CHANGED, globalConfig);

}

}

}

};

ViewRootImpl.addConfigCallback(configChangedCallback);

}

......

}

在代码 1 处,创建了一个 Instrumentation 工具和 Application 工具,可见 Application 不仅在利用法度榜样进程中有,在 SystemServer 进程中也有

在创建 Application 工具时,经由过程 getSystemContext() 措施可以获得System Context 工具

public ContextImpl getSystemContext() {

synchronized (this) {

if (mSystemContext == null) {

mSystemContext = ContextImpl.createSystemContext(this);

}

return mSystemContext;

}

}

在 getSystemContext() 措施中,终极调用了 ContextImpl.createSystemContext(ActivityThread mainThread) 措施创建了一个 System Context 工具,我们走到 ContextImpl 类中

class ContextImpl extends Context {

......

static ContextImpl createSystemContext(ActivityThread mainThread) {

LoadedApk packageInfo = new LoadedApk(mainThread);

ContextImpl context = new ContextImpl(null, mainThread, packageInfo, null, null, null, 0,

null);

context.setResources(packageInfo.getResources());

context.mResources.updateConfiguration(context.mResourcesManager.getConfiguration(),

context.mResourcesManager.getDisplayMetrics());

return context;

}

......

static ContextImpl createAppContext(ActivityThread mainThread, LoadedApk packageInfo) {

if (packageInfo == null) throw new IllegalArgumentException("packageInfo");

ContextImpl context = new ContextImpl(null, mainThread, packageInfo, null, null, null, 0,

null);

context.setResources(packageInfo.getResources());

return context;

}

......

}

在创建 System Context 工具时,起开创建了一个 LoadadApk 工具,然后经由过程 ContextImpl 构造措施创建了一个 Context 工具

2.3 SystemServiceManager 工具

然后再看下创建 SystemServiceManager 工具的创建

// Create the system service manager.

mSystemServiceManager = new SystemServiceManager(mSystemContext);

mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);

LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);

经由过程 SystemServiceManager 的构造措施创建一个 SystemServiceManager 工具,并将该工具添加到 LocalServices 中,这两个类的源码都不繁杂,简单阐发一下

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

在 SystemServiceManager 中都是经由过程反射创建 SystemService 中工具的,而且在 startService(@NonNull final SystemService service) 措施中,会将 SystemService 添加到 mServices 中,并调用 onStart() 措施

public class SystemServiceManager {

private final Context mContext;

// Services that should receive lifecycle events.

private final ArrayList mServices = new ArrayList();

......

SystemServiceManager(Context context) {

mContext = context;

}

@SuppressWarnings("unchecked")

public SystemService startService(String className) {

final Class serviceClass;

try {

serviceClass = (Class)Class.forName(className);

} catch (ClassNotFoundException ex) {

Slog.i(TAG, "Starting " + className);

throw new RuntimeException("Failed to create service " + className

+ ": service class not found, usually indicates that the caller should "

+ "have called PackageManager.hasSystemFeature() to check whether the "

+ "feature is available on this device before trying to start the "

+ "services that implement it", ex);

}

return startService(serviceClass);

}

publicT startService(Class 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 {

Constructor 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 = System.currentTimeMillis();

try {

service.onStart();

} catch (RuntimeException ex) {

throw new RuntimeException("Failed to start service " + service.getClass().getName()

+ ": onStart threw an exception", ex);

}

warnIfTooLong(System.currentTimeMillis() - time, service, "onStart");

}

......

}

LocalServices 中主要经由过程静态的 ArrayMap 持有所有的 Service 工具,它和 SystemServiceManager 有点类型,所不合的是,在 LocalServices 中持有的 Service 工具并不是 Binder 工具,只可以在同一进程中应用

public final class LocalServices {

private LocalServices() {}

private static final ArrayMap, Object> sLocalServiceObjects =

new ArrayMap, Object>();

public staticT getService(Class type) {

synchronized (sLocalServiceObjects) {

return (T) sLocalServiceObjects.get(type);

}

}

public staticvoid addService(Class type, T service) {

synchronized (sLocalServiceObjects) {

if (sLocalServiceObjects.containsKey(type)) {

throw new IllegalStateException("Overriding service registration");

}

sLocalServiceObjects.put(type, service);

}

}

}

2.4 启动 AMS 系统办事

在上面的先容中,一共有三种办事会被启动:系统向导办事(BootstrapServices)、核心办事(CoreServices)和其他办事(OtherServices),而 AMS 属于系统向导类办事

private void startBootstrapServices() {

Slog.i(TAG, "Reading configuration...");

final String TAG_SYSTEM_CONFIG = "ReadingSystemConfig";

traceBeginAndSlog(TAG_SYSTEM_CONFIG);

SystemServerInitThreadPool.get().submit(SystemConfig::getInstance, TAG_SYSTEM_CONFIG);

traceEnd();

// 在 Installer 中会创建一些关键的目录,比如:/data/user

traceBeginAndSlog("StartInstaller");

Installer installer = mSystemServiceManager.startService(Installer.class);

traceEnd();

// 创建一些设备相关的信息

traceBeginAndSlog("DeviceIdentifiersPolicyService");

mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);

traceEnd();

// 代码 1,启动 AMS

traceBeginAndSlog("StartActivityManager");

mActivityManagerService = mSystemServiceManager.startService(

ActivityManagerService.Lifecycle.class).getService();

// 将 SystemServiceManager 工具设置给 AMS 工具

mActivityManagerService.setSystemServiceManager(mSystemServiceManager);

// 将 installer 设置给 AMS 工具

mActivityManagerService.setInstaller(installer);

traceEnd();

......

// Now that the power manager has been started, let the activity manager

// initialize power management features.

traceBeginAndSlog("InitPowerManagement");

mActivityManagerService.initPowerManagement();

traceEnd();

......

// Set up the Application instance for the system process and get started.

traceBeginAndSlog("SetSystemProcess");

mActivityManagerService.setSystemProcess();

traceEnd();

......

}

......

private void startOtherServices() {

......

traceBeginAndSlog("SetWindowManagerService");

mActivityManagerService.setWindowManager(wm);

traceEnd();

......

mActivityManagerService.systemReady(() -> {

......

traceBeginAndSlog("StartSystemUI");

try {

startSystemUi(context, windowManagerF);

} catch (Throwable e) {

reportWtf("starting System UI", e);

}

traceEnd();

......

}

}

在代码 1 处启动 AMS 时,经由过程 ActivityManagerService.Lifecycle 这个类,如下所示,ActivityManagerService.Lifecycle 类很简单,承袭 SystemService,是一个 ActivityManagerService 的包装类

SystemServiceManager 经由过程 ActivityManagerService.Lifecycle 间接的持有了 AMS 的工具,然后调用了 AMS 的 initPowerManagement() 和 setSystemProcess() 措施

在 startOtherServices() 措施中,创建了 WMS 工具,并将 WMS 工具设置进 AMS 中,着末调用了 AMS 的 systemReady(final Runnable goingCallback, BootTimingsTraceLog traceLog) 措施,奉告 AMS 可以启动运行了

在 ActivityManagerService.Lifecycle 经由过程 AMS 的构造措施创建了一个 AMS 工具并调用了其 start() 措施

public static final class Lifecycle extends SystemService {

private final ActivityManagerService mService;

public Lifecycle(Context context) {

super(context);

mService = new ActivityManagerService(context);

}

@Override

public void onStart() {

mService.start();

}

public ActivityManagerService getService() {

return mService;

}

}

三. AMS 的启动流程

在上一节中,我们阐发到了 AMS 的构造措施和 start() 措施,这一节就经由过程这个进口,具体的阐发 AMS 的启动流程

3.1 AMS 的构造措施

public class ActivityManagerService extends IActivityManager.Stub

implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {

......

public ActivityManagerService(Context systemContext) {

LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);

// 用于测试,可轻忽

mInjector = new Injector();

// 设置 System Context 工具,此 systemContext 便是在 SystemServer 和 ActivityThread 中创建和应用的 System Context 工具

mContext = systemContext;

mFactoryTest = FactoryTest.getMode();

// 设置 ActivityThread 工具,便是在 SystemServer 中创建的 ActivityThread 工具

mSystemThread = ActivityThread.currentActivityThread();

mUiContext = mSystemThread.getSystemUiContext();

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

mPermissionReviewRequired = mContext.getResources().getBoolean(

com.android.internal.R.bool.config_permissionReviewRequired);

// 创建一个 Thread 和其对应的 Handler

mHandlerThread = new ServiceThread(TAG,

THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);

mHandlerThread.start();

mHandler = new MainHandler(mHandlerThread.getLooper());

mUiHandler = mInjector.getUiHandler(this);

mConstants = new ActivityManagerConstants(this, mHandler);

/* static; one-time init here */

if (sKillHandler == null) {

sKillThread = new ServiceThread(TAG + ":kill",

THREAD_PRIORITY_BACKGROUND, true /* allowIo */);

sKillThread.start();

sKillHandler = new KillHandler(sKillThread.getLooper());

}

// 创建 BroadcastQueue 前台广播工具,处置惩罚超不时长是 10s

mFgBroadcastQueue = new BroadcastQueue(this, mHandler,

"foreground", BROADCAST_FG_TIMEOUT, false);

// 创建 BroadcastQueue 后台广播工具,处置惩罚超不时长是 60s

mBgBroadcastQueue = new BroadcastQueue(this, mHandler,

"background", BROADCAST_BG_TIMEOUT, true);

mBroadcastQueues[0] = mFgBroadcastQueue;

mBroadcastQueues[1] = mBgBroadcastQueue;

// 创建 ActiveServices 工具,用于治理 ServiceRecord 工具

mServices = new ActiveServices(this);

// 创建 ProviderMap 工具,用于治理 ContentProviderRecord 工具

mProviderMap = new ProviderMap(this);

// 创建 AppErrors 工具,用于处置惩罚利用法度榜样的非常

mAppErrors = new AppErrors(mUiContext, this);

// 初始化 /data/system 目录

File dataDir = Environment.getDataDirectory();

File systemDir = new File(dataDir, "system");

systemDir.mkdirs();

// 初始化电池状态信息,进程状态 和 利用权限治理

mBatteryStatsService = new BatteryStatsService(systemDir, mHandler);

mBatteryStatsService.getActiveStatistics().readLocked();

mBatteryStatsService.scheduleWriteToDisk();

mOnBattery = DEBUG_POWER ? true

: mBatteryStatsService.getActiveStatistics().getIsOnBattery();

mBatteryStatsService.getActiveStatistics().setCallback(this);

mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));

// 启动 Android 权限反省办事,注册对应的回调接口

mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);

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 (mAppOpsService.checkOperation(op, uid, packageName)

!= AppOpsManager.MODE_ALLOWED) {

runInBackgroundDisabled(uid);

}

}

}

});

mGrantFile = new AtomicFile(new File(systemDir, "urigrants.xml"));

mUserController = new UserController(this);

mVrController = new VrController(this);

GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",

ConfigurationInfo.GL_ES_VERSION_UNDEFINED);

if (SystemProperties.getInt("sys.use_fifo_ui", 0) != 0) {

mUseFifoUiScheduling = true;

}

mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));

mTempConfig.setToDefaults();

mTempConfig.setLocales(LocaleList.getDefault());

mConfigurationSeq = mTempConfig.seq = 1;

//创建 ActivityStackSupervisor 工具,是 AMS 中 ActivityRecord 和 TaskRecord 治理和调整的紧张类

mStackSupervisor = createStackSupervisor();

mStackSupervisor.onConfigurationChanged(mTempConfig);

mKeyguardController = mStackSupervisor.mKeyguardController;

mCompatModePackages = new CompatModePackages(this, systemDir, mHandler);

mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);

mTaskChangeNotificationController =

new TaskChangeNotificationController(this, mStackSupervisor, mHandler);

// 创建 ActivityStarter 工具,用于启动 Activity

mActivityStarter = new ActivityStarter(this, mStackSupervisor);

// 近来应用的 RecentTasks

mRecentTasks = new RecentTasks(this, mStackSupervisor);

// 创建一个用于更新 CPU 信息的线程

mProcessCpuThread = new Thread("CpuTracker") {

@Override

public void run() {

synchronized (mProcessCpuTracker) {

mProcessCpuInitLatch.countDown();

mProcessCpuTracker.init();

}

while (true) {

try {

try {

synchronized(this) {

final long now = SystemClock.uptimeMillis();

long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;

long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;

//Slog.i(TAG, "Cpu delay=" + nextCpuDelay

//+ ", write delay=" + nextWriteDelay);

if (nextWriteDelay0) {

mProcessCpuMutexFree.set(true);

this.wait(nextCpuDelay);

}

}

} catch (InterruptedException e) {

}

updateCpuStatsNow();

} catch (Exception e) {

Slog.e(TAG, "Unexpected exception collecting process stats", e);

}

}

}

};

// 将此 AMS 工具添加到 Watchdog 中

Watchdog.getInstance().addMonitor(this);

Watchdog.getInstance().addThread(mHandler);

}

......

}

在 AMS 的构造措施中主要做了以下工作:

初始化一些工具属性,包括 Context、ActivityThread、ServiceThread、MainHandler、ActivityManagerConstants 等工具

创建和治理四大年夜组件相关的类工具,包括 BroadcastQueue、ActiveServices、ProviderMap、ActivityStackSupervisor、RecentTasks 和 ActivityStarter 等工具

创建一个 CPU 监控线程 mProcessCpuThread

3.2 一些初始化措施

在 start() 措施中,主要完成了以下两个事:

启动 CPU 监控线程,在启动 CPU 监控线程之前,首先将进程复位

注册电池状态办事和权限治理办事

private void start() {

// 在启动 CPU 监控线程之前,首先将进程复位

removeAllProcessGroups();

mProcessCpuThread.start();

// 注册电池状态和权限治理办事

mBatteryStatsService.publish(mContext);

mAppOpsService.publish(mContext);

Slog.d("AppOps", "AppOpsService published");

LocalServices.addService(ActivityManagerInternal.class, new LocalService());

// Wait for the synchronized block started in mProcessCpuThread,

// so that any other acccess 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");

}

}

除 start() 措施之外,还调用了 initPowerManagement()、setSystemProcess() 和 setWindowManager(WindowManagerService wm) 措施

// 初始化一些 PowerManager 相关类

public void initPowerManagement() {

mStackSupervisor.initPowerManagement();

mBatteryStatsService.initPowerManagement();

mLocalPowerManager = LocalServices.getService(PowerManagerInternal.class);

PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);

mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");

mVoiceWakeLock.setReferenceCounted(false);

}

// 初始化一些系统信息,包括 meminfo、gfxinfo、dbinfo、cpuinfo 等信息

// 并创建一个系统进行信息类 ProcessRecord 工具

public void setSystemProcess() {

try {

ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true);

ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);

ServiceManager.addService("meminfo", new MemBinder(this));

ServiceManager.addService("gfxinfo", new GraphicsBinder(this));

ServiceManager.addService("dbinfo", new DbBinder(this));

if (MONITOR_CPU_USAGE) {

ServiceManager.addService("cpuinfo", new CpuBinder(this));

}

ServiceManager.addService("permission", new PermissionController(this));

ServiceManager.addService("processinfo", new ProcessInfoService(this));

ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(

"android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);

mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());

synchronized (this) {

ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0);

app.persistent = true;

app.pid = MY_PID;

app.maxAdj = ProcessList.SYSTEM_ADJ;

app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);

synchronized (mPidsSelfLocked) {

mPidsSelfLocked.put(app.pid, app);

}

updateLruProcessLocked(app, false, null);

updateOomAdjLocked();

}

} catch (PackageManager.NameNotFoundException e) {

throw new RuntimeException(

"Unable to find android system package", e);

}

}

// 持有 WMS 工具的引用,并为 mStackSupervisor 和 mActivityStarter 工具设置 WMS 工具

public void setWindowManager(WindowManagerService wm) {

mWindowManager = wm;

mStackSupervisor.setWindowManager(wm);

mActivityStarter.setWindowManager(wm);

}

在所有初始化完成之后,会调用 systemReady(final Runnable goingCallback, BootTimingsTraceLog traceLog) 措施

public void systemReady(final Runnable goingCallback, BootTimingsTraceLog traceLog) {

synchronized(this) {

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

}

return;

}

// 调用 mVrController、mUserController 等工具的 onSystemReady() 措施

mLocalDeviceIdleController

= LocalServices.getService(DeviceIdleController.LocalService.class);

mAssistUtils = new AssistUtils(mContext);

mVrController.onSystemReady();

// Make sure we have the current profile info, since it is needed for security checks.

mUserController.onSystemReady();

mRecentTasks.onSystemReadyLocked();

mAppOpsService.systemReady();

mSystemReady = true;

}

......

// 启动系统 Home 利用法度榜样,也便是 Launcher 利用

startHomeActivityLocked(currentUserId, "systemReady");

......

}

systemReady(final Runnable goingCallback, BootTimingsTraceLog traceLog) 措施调完之后,AMS 系统办事大年夜概的启动流程就阐发完成了,启动时序图如下所示

AMS1.png

图片滥觞 ActivityManagerService启动解析

您可能还会对下面的文章感兴趣: