我们知道,在zygote进行初始化时,会调用startSystemServer方法来初始化各种servcie,其中包括ActivityMangerService,现在我们就来看看ActivityMangerService是如何初始化的。我们从AMS被初始化的地方开起,也就是 SystemServer这个类
它的源码位于frameworks/base/services/java/com/android/server/SystemServer.java,这个类主要的做的事情有这几件
- ①初始化native service
- ②初始化系统上下文
- ③创建system service manager
- ④startBootstrapServices
- ⑤startCoreServices
- ⑥startOtherServices
我们再来看看SystemServer的启动时序图
下面再大致分析一下SystemServer的源码
private void run() {
……
//1、虚拟机内存初始化
VMRuntime.getRuntime().clearGrowthLimit();
VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
……
//2、创建消息队列
Looper.prepareMainLooper();
//3、初始化 native services.
System.loadLibrary("android_servers");
//4、初始化系统上下文
createSystemContext();
//5、创建system service manager.
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
// 为初始化任务准备线程池
SystemServerInitThreadPool.get();
// Start services.
try {
//6、启动BootstrapServices,CoreServices,OtherServices
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();
}
// Loop forever.
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
现在我们已经了解了SystemSever大致所做的事情,这篇文章讲的是ActivityManagerService,所以对SystemSever便不再详细的讲解,从时序图中看到ActivityManagerService是从初始化系统上下时启动的,我们便从源码中的4,初始系统上下文这一点开始进一步的讲解,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);
}
可以看到,里面调用的是ActivityThread的systemMain方法,然后获取的是ActivityThread的SystemContext,ActivityThread相当于是每个应用的应用的主线程,负责调度和执行activities、broadcasts和其它操作。我们接着看看systemMain方法
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;
}
这个方法实际就是new了一个ActivityThread,并且调用了attach方法,attach方法做的事情主要有以下几件
①判断时候从系统启动,如果不是从系统系统,则ApplicationThread把mAppThread attach到系统进程system_process,以便system_process控制当前应用的ActivityThread,这一步操作我们之后再详解,因为现在从系统启动的ActivityThread,所以attach方法实际会执行以下几步操作
- 创建Instrumentation,Instrumentation是Android中的一个工具类
- 执行ContextImpl.createAppContext方法,也就是创建Context
- 执行context.mPackageInfo.makeApplication方法,创建InitialApplication
- 调用InitialApplication.onCreate()
②注册Configuration变化的回调通知
下面我们看看attach方法的源码
private void attach(boolean system) {
//将创建出的ActivityThread保存在类的静态变量sCurrentActivityThread,AMS中的大量操作将会依赖于这个ActivityThread
sCurrentActivityThread = this;
mSystemThread = system;
if (!system) {
//非系统启动
……
final IActivityManager mgr = ActivityManager.getService();
try {
//将mAppThread关联到ActivityManager中
mgr.attachApplication(mAppThread);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
……
} else {
//从System启动
android.ddm.DdmHandleAppName.setAppName("system_process",
UserHandle.myUserId());
try {
//创建Instrumentation,AppContext,Application
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);
}
}
//注册Configuration变化的回调通知
ViewRootImpl.ConfigChangedCallback configChangedCallback
= (Configuration globalConfig) -> {
//当系统配置发生变化时(例如系统语言发生变化),回调该接口,通知资源改变
synchronized (mResourcesManager) {
if (mResourcesManager.applyConfigurationToResourcesLocked(globalConfig,
null /* compat */)) {
updateLocaleListFromAppContext(mInitialApplication.getApplicationContext(),
mResourcesManager.getConfiguration().getLocales());
if (mPendingConfiguration == null
|| mPendingConfiguration.isOtherSeqNewer(globalConfig)) {
mPendingConfiguration = globalConfig;
sendMessage(H.CONFIGURATION_CHANGED, globalConfig);
}
}
}
};
ViewRootImpl.addConfigCallback(configChangedCallback);
}
看完了ActivityThread.systemMain()方法,我们再来看看getSystemContext()方法
public ContextImpl getSystemContext() {
synchronized (this) {
if (mSystemContext == null) {
mSystemContext = ContextImpl.createSystemContext(this);
}
return mSystemContext;
}
}
它其实是通过调用ContextImpl的createSystemContext方法,在进步看看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;
}
可以看到ContextImpl是通过LoadedApk和当前的mainThread创建的SystemContext,此时的LoadedApk还只是个空壳,当PKMS启动后,完成对应的解析,AMS会重新设置这个LoadedApk,至此,过程4中的创建系统上下文已经看完了,我们接着看看过程6中的startBootstrapServices方法
private void startBootstrapServices() {
……
//启动Installer
Installer installer = mSystemServiceManager.startService(Installer.class);
//启动DeviceIdentifiersPolicyService
mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);
//启动mActivityManagerService
mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
//启动PowerManagerService
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
mActivityManagerService.initPowerManagement();
// Bring up recovery system in case a rescue party needs a reboot
if (!SystemProperties.getBoolean("config.disable_noncore", false)) {e");
mSystemServiceManager.startService(RecoverySystemService.class);
}
// Now that we have the bare essentials of the OS up and running, take
// note that we just booted, which might send out a rescue party if
// we're stuck in a runtime restart loop.
RescueParty.noteBoot(mSystemContext);
// Manages LEDs and display backlight so we need it to bring up the display.
mSystemServiceManager.startService(LightsService.class);
// Display manager is needed to provide display metrics before package manager
// starts up.
mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
// We need the default display before we can initialize the package manager.
mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
// Only run "core" apps if we're encrypting the device.
String cryptState = SystemProperties.get("vold.decrypt");
if (ENCRYPTING_STATE.equals(cryptState)) {
Slog.w(TAG, "Detected encryption in progress - only parsing core apps");
mOnlyCore = true;
} else if (ENCRYPTED_STATE.equals(cryptState)) {
Slog.w(TAG, "Device encrypted - only parsing core apps");
mOnlyCore = true;
}
// Start the package manager.
if (!mRuntimeRestart) {
MetricsLogger.histogram(null, "boot_package_manager_init_start",
(int) SystemClock.elapsedRealtime());
}
mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
mFirstBoot = mPackageManagerService.isFirstBoot();
mPackageManager = mSystemContext.getPackageManager();
if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
MetricsLogger.histogram(null, "boot_package_manager_init_ready",
(int) SystemClock.elapsedRealtime());
}
// Manages A/B OTA dexopting. This is a bootstrap service as we need it to rename
// A/B artifacts after boot, before anything else might touch/need them.
// Note: this isn't needed during decryption (we don't have /data anyways).
if (!mOnlyCore) {
boolean disableOtaDexopt = SystemProperties.getBoolean("config.disable_otadexopt",
false);
if (!disableOtaDexopt) {
traceBeginAndSlog("StartOtaDexOptService");
try {
OtaDexoptService.main(mSystemContext, mPackageManagerService);
} catch (Throwable e) {
reportWtf("starting OtaDexOptService", e);
} finally {
traceEnd();
}
}
}
mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
// Initialize attribute cache used to cache resources from packages.
traceBeginAndSlog("InitAttributerCache");
AttributeCache.init(mSystemContext);
traceEnd();
// Set up the Application instance for the system process and get started.
mActivityManagerService.setSystemProcess();
// DisplayManagerService needs to setup android.display scheduling related policies
// since setSystemProcess() would have overridden policies due to setProcessGroup
mDisplayManagerService.setupSchedulerPolicies();
// Manages Overlay packages
mSystemServiceManager.startService(new OverlayManagerService(mSystemContext, installer));
// The sensor service needs access to package manager service, app ops
// service, and permissions service, therefore we start it after them.
// Start sensor service in a separate thread. Completion should be checked
// before using it.
mSensorServiceStart = SystemServerInitThreadPool.get().submit(() -> {
BootTimingsTraceLog traceLog = new BootTimingsTraceLog(
SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
traceLog.traceBegin(START_SENSOR_SERVICE);
startSensorService();
traceLog.traceEnd();
}, START_SENSOR_SERVICE);
}
上面的方法就不详细分析,通过方法名,每个方法启动的服务已经很清楚了。可以看到ActivityManagerService也在这儿被启动,这时我们可以开始分析ActivityManagerService的源码了,从上面的源码可以看到,与AMS相关的代码主要是这几句
//启动ams
mActivityManagerService =mSystemServiceManager.startService(ActivityManagerService.Lifecycle.class).getService();
//将SystemServiceManager添加到AMS
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
//将installer添加到AMS
mActivityManagerService.setInstaller(installer);
……
//将SystemServer进程添加到AMS中调度管理
mActivityManagerService.setSystemProcess();
SystemServiceManager是通过ActivityManagerService.Lifecycle.class来启动AMS的,所以我们先看看ActivityManagerService.Lifecycle.class,AMS的源码位于/frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
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;
}
}
Lifecycle 做的事是new了一个ActivityManagerService,然后启动start方法,我们接着来看看ActivityManagerService的构造函数,AMS的构造方法主要做了这些事情
- 初始化context环境
- 初始化 工作的线程,handler,UiHandler
- 广播队列BroadcastQueue初始化
- 创建Service 和Provider变量
- 初始化系统数据存放目录
- 初始化系统数据存放目录
- 启动Android的权限检查服务
- 创建多用户管理器
- 初始化资源配置信息
- 初始化ActivityStackSupervisor
- 监控和定时更新系统CPU信息
public ActivityManagerService(Context systemContext) {
//1、初始化context环境
-------------------------------------------------------------------------------------
mContext = systemContext;
mSystemThread = ActivityThread.currentActivityThread();
mUiContext = mSystemThread.getSystemUiContext();
-------------------------------------------------------------------------------------
//2、初始化 工作的线程,handler,UiHandler
-------------------------------------------------------------------------------------
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);
if (sKillHandler == null) {
sKillThread = new ServiceThread(TAG + ":kill",
THREAD_PRIORITY_BACKGROUND, true /* allowIo */);
sKillThread.start();
sKillHandler = new KillHandler(sKillThread.getLooper());
}
-------------------------------------------------------------------------------------
//3、广播队列BroadcastQueue初始化:前台广播队列和后台广播队列,前台的超时时间为10s,后台的超时时间为60s
-------------------------------------------------------------------------------------
mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
"foreground", BROADCAST_FG_TIMEOUT, false);
mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
"background", BROADCAST_BG_TIMEOUT, true);
mBroadcastQueues[0] = mFgBroadcastQueue;
mBroadcastQueues[1] = mBgBroadcastQueue;
-------------------------------------------------------------------------------------
//4、创建Service 和Provider ,用于存储Service 和Provider信息
-------------------------------------------------------------------------------------
mServices = new ActiveServices(this);
mProviderMap = new ProviderMap(this);
-------------------------------------------------------------------------------------
//5、初始化系统数据存放目录:/data/system/
-------------------------------------------------------------------------------------
File dataDir = Environment.getDataDirectory();
File systemDir = new File(dataDir, "system");
systemDir.mkdirs();
-------------------------------------------------------------------------------------
//6、初始化电池状态信息,进程状态 和 应用权限管理
mBatteryStatsService = new BatteryStatsService(systemDir, mHandler);
mBatteryStatsService.getActiveStatistics().readLocked();
mBatteryStatsService.scheduleWriteToDisk();
mOnBattery = DEBUG_POWER ? true
: mBatteryStatsService.getActiveStatistics().getIsOnBattery();
mBatteryStatsService.getActiveStatistics().setCallback(this);
-------------------------------------------------------------------------------------
//7、启动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);
}
}
}
});
-------------------------------------------------------------------------------------
//8、创建多用户管理器
-------------------------------------------------------------------------------------
mUserController = new UserController(this);
-------------------------------------------------------------------------------------
//9、获取OpenGL版本
-------------------------------------------------------------------------------------
GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
if (SystemProperties.getInt("sys.use_fifo_ui", 0) != 0) {
mUseFifoUiScheduling = true;
}
-------------------------------------------------------------------------------------
//10、初始化资源配置信息
-------------------------------------------------------------------------------------
mTempConfig.setToDefaults();
mTempConfig.setLocales(LocaleList.getDefault());
mConfigurationSeq = mTempConfig.seq = 1;
mKeyguardController = mStackSupervisor.mKeyguardController;
//当APK所运行的设备不满足要求时,AMS会根据xml设置的参数以采用屏幕兼容的方式运行该APK
mCompatModePackages = new CompatModePackages(this, systemDir, mHandler);
//过滤一些Intent
mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
//11、初始化ActivityStackSupervisor,ActivityStackSupervisor是AMS中用来管理Activity启动和调度的核心类 ,用于管理和监控AMS维护的Activity Task信息
-------------------------------------------------------------------------------------
mStackSupervisor = createStackSupervisor();
mStackSupervisor.onConfigurationChanged(mTempConfig);
mTaskChangeNotificationController =new TaskChangeNotificationController(this, mStackSupervisor, mHandler);
// 最近任务,Activity,Task管理
mActivityStarter = new ActivityStarter(this, mStackSupervisor);
mRecentTasks = new RecentTasks(this, mStackSupervisor);
-------------------------------------------------------------------------------------
//12、创建一个新线程,用于监控和定时更新系统CPU信息,30分钟更新一次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 (nextWriteDelay < nextCpuDelay) {
nextCpuDelay = nextWriteDelay;
}
if (nextCpuDelay > 0) {
mProcessCpuMutexFree.set(true);
this.wait(nextCpuDelay);
}
}
} catch (InterruptedException e) {
}
updateCpuStatsNow();
} catch (Exception e) {
Slog.e(TAG, "Unexpected exception collecting process stats", e);
}
}
}
};
-------------------------------------------------------------------------------------
}
我们再来看看AMS的start函数,start方法里面做的主要有这几件事
- 启动CPU监控线程。该线程将会开始统计不同进程使用CPU的情况
- 发布一些服务,如BatteryStatsService、AppOpsService(权限管理相关)和本地实现的继承ActivityManagerInternal的服务
private void start() {
//完成统计前的复位工作
removeAllProcessGroups();
//开始监控进程的CPU使用情况
mProcessCpuThread.start();
//注册服务
mBatteryStatsService.publish(mContext);
mAppOpsService.publish(mContext);
LocalServices.addService(ActivityManagerInternal.class, new LocalService());
}
了解了AMS的启动,我们在来看看mActivityManagerService.setSystemProcess()这行代码,setSystemProcess是为了让AMS来调度管理systemServer,我们看看里面的源码
public void setSystemProcess() {
try {
//1、向ServiceManager注册服务
————————————————————————————————————————————————————————————————————
//注册自己
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));
用于输出进程的CPU使用情况
if (MONITOR_CPU_USAGE) {
ServiceManager.addService("cpuinfo", new CpuBinder(this));
}
//注册权限管理服务
ServiceManager.addService("permission", new PermissionController(this));
//注册获取进程信息的服务
ServiceManager.addService("processinfo", new ProcessInfoService(this));
————————————————————————————————————————————————————————————————————
//2、向PKMS查询package名为“android”的应用的ApplicationInfo
————————————————————————————————————————————————————————————————————
ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
"android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
————————————————————————————————————————————————————————————————————
//3、调用installSystemApplicationInfo方法
————————————————————————————————————————————————————————————————————
mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
————————————————————————————————————————————————————————————————————
4、将SystemServer进程加入到AMS进程管理机制中,跟应用进程一致
————————————————————————————————————————————————————————————————————
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);
}
————————————————————————————————————————————————————————————————————
}
我们先来看看3,mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader())这个方法所做的事情,我们进到ActivityThread中查看installSystemApplicationInfo的源码
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();
}
}
其中
getSystemContext().installSystemApplicationInfo(info, classLoader);
getSystemUiContext().installSystemApplicationInfo(info, classLoader);
都是调用的ContextImpl中的installSystemApplicationInfo,所以我们直接看看ContextImpl中的installSystemApplicationInfo方法,
void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) {
mPackageInfo.installSystemApplicationInfo(info, classLoader);
}
在前面提到的的ContextImpl.createSystemContext中我们提到了ContextImpl会根据LoadedApk和activitythread创建SystemContext,前面也说过此时的PKMS还没有,所以LoadedApk是一个空壳,在这个时候installSystemApplicationInfo实际就是将“android”对应的ApplicationInfo添加到之前创建的LoadedApk中去,所以这个时候,我们对SystemContext到底是什么也清楚了。
但步骤3的工作做完后,步骤4便将SystemServer的运行环境和一个进程管理结构对应起来,并进行统一的管理
我们对startBootstrapServices这个方法中AMS相关的代码分析完了,接着我们在看看startOtherServices这个方法里面AMS的代码
private void startOtherServices() {
...........
mActivityManagerService.installSystemProviders();
...........
mActivityManagerService.systemReady(……);
}
我们先来着看AMS中的installSystemProviders方法,它主要做的事情有两件
①取出系统级的provider
②安装provider
installSystemProviders主要是加载运行在SystemServer进程中的ContentProvider,即SettingsProvider.apk (定义于frameworks/base/packages/SettingsProvider)
public final void installSystemProviders() {
List<ProviderInfo> providers;
synchronized (this) {
//AMS根据进程名取出SystemServer对应的ProcessRecord
ProcessRecord app = mProcessNames.get("system", SYSTEM_UID);
//1、得到该ProcessRecord对应的ProviderInfo
providers = generateApplicationProvidersLocked(app);
//过滤掉非系统级的Provider
if (providers != null) {
for (int i=providers.size()-1; i>=0; i--) {
ProviderInfo pi = (ProviderInfo)providers.get(i);
if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Slog.w(TAG, "Not installing system proc provider " + pi.name
+ ": not system .apk");
providers.remove(i);
}
}
}
}
if (providers != null) {
//2、安装Provider
mSystemThread.installSystemProviders(providers);
}
mConstants.start(mContext.getContentResolver());
//创建ContentObserver监控Settings数据库中Secure、System和Global表的变化
mCoreSettingsObserver = new CoreSettingsObserver(this);
//创建ContentObserver监控Settings数据库中字体大小的变化
mFontScaleSettingObserver = new FontScaleSettingObserver();
RescueParty.onSettingsProviderPublished(mContext);
}
接着在看看最后的操作,systemReady中做的事情,systemReady做的事情主要有下面几件
- 1、调用一些关键服务SystemReady相关的函数,等待AMS初始完
- 2、收集已经启动的进程并杀死
- 3、系统准备好后回调传入的Runnable
- 4、启动Home
public void systemReady(final Runnable goingCallback, BootTimingsTraceLog traceLog) {
//1、调用一些关键服务SystemReady相关的函数,进行一些等待AMS初始完,才能进行的工作
————————————————————————————————————————————————————————————————————————
synchronized(this) {
if (mSystemReady) {
if (goingCallback != null) {
goingCallback.run();
}
return;
}
mLocalDeviceIdleController
= LocalServices.getService(DeviceIdleController.LocalService.class);
mAssistUtils = new AssistUtils(mContext);
mVrController.onSystemReady();
mUserController.onSystemReady();
mRecentTasks.onSystemReadyLocked();
mAppOpsService.systemReady();
mSystemReady = true;
}
————————————————————————————————————————————————————————————————————————
//2、收集已经启动的进程并杀死
————————————————————————————————————————————————————————————————————————
ArrayList<ProcessRecord> procsToKill = null;
synchronized(mPidsSelfLocked) {
for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
ProcessRecord proc = mPidsSelfLocked.valueAt(i);
if (!isAllowedWhileBooting(proc.info)){
if (procsToKill == null) {
procsToKill = new ArrayList<ProcessRecord>();
}
procsToKill.add(proc);
}
}
}
synchronized(this) {
if (procsToKill != null) {
for (int i=procsToKill.size()-1; i>=0; i--) {
ProcessRecord proc = procsToKill.get(i);
Slog.i(TAG, "Removing system update proc: " + proc);
removeProcessLocked(proc, true, false, "system update done");
}
}
//系统准备完毕
mProcessesReady = true;
}
————————————————————————————————————————————————————————————————————————
//根据数据库和资源文件,获取一些配置参数
————————————————————————————————————————————————————————————————————————
retrieveSettings();
final int currentUserId;
synchronized (this) {
//得到当前的用户ID
currentUserId = mUserController.getCurrentUserIdLocked();
readGrantedUriPermissionsLocked();
}
————————————————————————————————————————————————————————————————————————
//3、系统准备好后回调传入的Runnable
————————————————————————————————————————————————————————————————————————
if (goingCallback != null) goingCallback.run();
————————————————————————————————————————————————————————————————————————
……
————————————————————————————————————————————————————————————————————————
//调用所有系统服务的onStartUser接口
mSystemServiceManager.startUser(currentUserId);
synchronized (this) {
/*启动从PKMS中得到persistent为1的ApplicationInfo
并通过startProcessLocked方法启动且发消息给zygote,fork进程
在AndroidManifest.xml有android:persistent这个属性,persistent为1其实就是常驻进程
*/
startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE);
// 启动 initial activity.
mBooting = true;
// Enable home activity for system user, so that the system can always boot. We don't
// do this when the system user is not setup since the setup wizard should be the one
// to handle home activity in this case.
if (UserManager.isSplitSystemUser() &&
Settings.Secure.getInt(mContext.getContentResolver(),
Settings.Secure.USER_SETUP_COMPLETE, 0) != 0) {
ComponentName cName = new ComponentName(mContext, SystemUserHomeActivity.class);
try {
AppGlobals.getPackageManager().setComponentEnabledSetting(cName,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0,
UserHandle.USER_SYSTEM);
} catch (RemoteException e) {
throw e.rethrowAsRuntimeException();
}
}
————————————————————————————————————————————————————————————————————————
//4、启动Home
————————————————————————————————————————————————————————————————————————
startHomeActivityLocked(currentUserId, "systemReady");
————————————————————————————————————————————————————————————————————————
……
// 5. 发送账户启动的广播
————————————————————————————————————————————————————————————————————————
long ident = Binder.clearCallingIdentity();
try {
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, intent,
null, null, 0, null, null, null, AppOpsManager.OP_NONE,
null, false, false, MY_PID, SYSTEM_UID,
currentUserId);
intent = new Intent(Intent.ACTION_USER_STARTING);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
broadcastIntentLocked(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)
throws RemoteException {
}
}, 0, null, null,
new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
} catch (Throwable t) {
Slog.wtf(TAG, "Failed sending first user broadcasts", t);
} finally {
Binder.restoreCallingIdentity(ident);
}
————————————————————————————————————————————————————————————————————————
//恢复 top activity,因为现在没有任何启动的 activity, 将会启动 startHomeActivityLocked,启动 HOME
mStackSupervisor.resumeFocusedStackTopActivityLocked();
mUserController.sendUserSwitchBroadcastsLocked(-1, currentUserId);
}
}
我们先来看看过程3中的runalbe回到方法,这个方法在SystemServer中
//启动NativeCrashListener监听"/data/system/ndebugsocket"中的信息,监听debuggerd传入的信息
mSystemServiceManager.startBootPhase(SystemSermActivityManagerService.startObservingNativeCrashes();
final String WEBVIEW_PREPARATION = "WebViewFactoryPreparation";
Future<?> webviewPrep = null;
if (!mOnlyCore) {
webviewPrep = SystemServerInitThreadPool.get().submit(() -> {
Slog.i(TAG, WEBVIEW_PREPARATION);
BootTimingsTraceLog traceLog = new BootTimingsTraceLog(
SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
traceLog.traceBegin(WEBVIEW_PREPARATION);
ConcurrentUtils.waitForFutureNoInterrupt(mZygotePreload, "Zygote preload");
mZygotePreload = null;
mWebViewUpdateService.prepareWebViewInSystemServer();
traceLog.traceEnd();
}, WEBVIEW_PREPARATION);
}
//启动SystemUi
startSystemUi(context, windowManagerF);
if (networkScoreF != null) networkScoreF.systemReady();
if (networkManagementF != null) networkManagementF.systemReady();
CountDownLatch networkPolicyInitReadySignal = null;
if (networkPolicyF != null) {
networkPolicyInitReadySignal = networkPolicyF
.networkScoreAndNetworkManagementServiceReady();
}
if (networkStatsF != null) networkStatsF.systemReady();
if (connectivityF != null) connectivityF.systemReady();
if (networkPolicyF != null) {
networkPolicyF.systemReady(networkPolicyInitReadySignal);
}
Watchdog.getInstance().start();
// Wait for all packages to be prepared
mPackageManagerService.waitForAppDataPrepared();
// It is now okay to let the various system services start their
// third party code...
// confirm webview completion before starting 3rd party
if (webviewPrep != null) {
ConcurrentUtils.waitForFutureNoInterrupt(webviewPrep, WEBVIEW_PREPARATION);
}
mSystemServiceManager.startBootPhase(
SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
if (locationF != null) locationF.systemRunning();
if (countryDetectorF != null) countryDetectorF.systemRunning();
if (networkTimeUpdaterF != null) networkTimeUpdaterF.systemRunning();
if (commonTimeMgmtServiceF != null) {
commonTimeMgmtServiceF.systemRunning();
}
if (inputManagerF != null) inputManagerF.systemRunning();
if (telephonyRegistryF != null) telephonyRegistryF.systemRunning();
if (mediaRouterF != null) mediaRouterF.systemRunning();
if (mmsServiceF != null) mmsServiceF.systemRunning();
if (networkScoreF != null) networkScoreF.systemRunning();
// TODO: Switch from checkService to getService once it's always
// in the build and should reliably be there.
final IIncidentManager incident = IIncidentManager.Stub.asInterface(
ServiceManager.checkService("incident"));
if (incident != null) incident.systemRunning();
这个回调方法主要是在ams初始化完成后,会调用大量服务的onBootPhase函数、一些对象的systemReady函数或systemRunning函数,接着我们再看看过程4,启动HomeActivity,也就是launcher
boolean startHomeActivityLocked(int userId, String reason) {
Intent intent = getHomeIntent();
ActivityInfo aInfo = resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
if (aInfo != null) {
intent.setComponent(new ComponentName(aInfo.applicationInfo.packageName, aInfo.name));
// Don't do this if the home app is currently being
// instrumented.
aInfo = new ActivityInfo(aInfo);
aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
ProcessRecord app = getProcessRecordLocked(aInfo.processName,
aInfo.applicationInfo.uid, true);
if (app == null || app.instr == null) {
intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
final int resolvedUserId = UserHandle.getUserId(aInfo.applicationInfo.uid);
// For ANR debugging to verify if the user activity is the one that actually
// launched.
// //启动home
final String myReason = reason + ":" + userId + ":" + resolvedUserId;
mActivityStarter.startHomeActivityLocked(intent, aInfo, myReason);
}
} else {
Slog.wtf(TAG, "No home screen found for " + intent, new Throwable());
}
return true;
}
可以看到这个方法里面主要是通过mActivityStarter.startHomeActivityLocked(intent, aInfo, myReason)来启动launcher,关于Activity的启动,会专门用一篇文章来分析,在这里就不深入讲了。至此,AMS的全部启动流程也分析完了,我们再来看看AMS启动的时序图,回忆总结一下。