AMS分析笔记
ActivityManagerService是Android系统中一个特别重要的系统服务,也是我们上层APP打交道最多的系 统服务之一。ActivityManagerService(以下简称AMS) 主要负责四大组件的启动、切换、调度以及应 用进程的管理和调度工作。所有的APP应用都需要 与AMS打交道
Activity Manager的组成主要分为以下几个部分:
1.服务代理:由ActivityManagerProxy实现,用于与Server端提供的系统服务进行进程间通信
2.服务中枢:ActivityManagerNative继承自Binder并实现IActivityManager,它提供了服务接口和
Binder接口的相互转化功能,并在内部存储服务代理对像,并提供了getDefault方法返回服务代理
3.Client:由ActivityManager封装一部分服务接口供Client调用。ActivityManager内部通过调用
ActivityManagerNative的getDefault方法,可以得到一个ActivityManagerProxy对像的引用,进而通过 该代理对像调用远程服务的方法
4.Server:由ActivityManagerService实现,提供Server端的系统服务
1 AMS启动过程分析
在分析AMS之前,先简单介绍一下Android系统的启动流程,因为AMS的启动就是在Android启动过程中。先分析一下Android系统启动流程:
1.1 Android系统启动流程
上图简要的介绍了Android系统的启动流程,启动过程中最重要的就是init进程,init进程属于用户态的1号进程,init进程会启动Zygote进程,然后Zygote就会创建它的“大儿子” System Server进程。其中AMS启动就是在System Server启动过程中进行的初始化。刚刚提到了Zygote进程,那看一下Zygote进程的具体启动。
1.2 Zygote进程启动
上面的Android启动过程中,可以了解到Zygote启动是在init进程中拉起来的,那么我们分析一下Zygote的启动进程:
Zygote其实就是一个孵化器,他不仅能孵化系统进程,APP的进程也是Zygote孵化出来的。所以我们后续的所有进程都是通过Zygote孵化的,所以Zygote是非常重要的一个模块。
1.3 System Server进程启动
System Server进程是分很多阶段的,比如根据PHASE值的不同,划分了不同阶段的启动工作。在System Server里面就会启动各种各样的服务,其中AMS服务就是在System Server里面启动的。AMS是在SystemServer中被添加的, 所以先到SystemServer中查看初始化:
// frameworks/base/services/java/com/android/server/SystemServer.java
/**
* The main entry point from zygote.
*/
public static void main(String[] args) {
new SystemServer().run();
}
这个main方法是启动SystemServer的入口,zygote启动SystemServer是通过反射的方式调用到main方法中,接下来就是执行run方法:
// frameworks/base/services/java/com/android/server/SystemServer.java
private void run() {
try {
traceBeginAndSlog("InitBeforeStartServices");
// If a device's clock is before 1970 (before 0), a lot of
// APIs crash dealing with negative numbers, notably
// java.io.File#setLastModified, so instead we fake it and
// hope that time from cell towers or NTP fixes it shortly.
if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
Slog.w(TAG, "System clock is before 1970; setting to 1970.");
SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
}
//
// Default the timezone property to GMT if not set.
//
String timezoneProperty = SystemProperties.get("persist.sys.timezone");
if (timezoneProperty == null || timezoneProperty.isEmpty()) {
Slog.w(TAG, "Timezone not set; setting to GMT.");
SystemProperties.set("persist.sys.timezone", "GMT");
}
// If the system has "persist.sys.language" and friends set, replace them with
// "persist.sys.locale". Note that the default locale at this point is calculated
// using the "-Duser.locale" command line flag. That flag is usually populated by
// AndroidRuntime using the same set of system properties, but only the system_server
// and system apps are allowed to set them.
//
// NOTE: Most changes made here will need an equivalent change to
// core/jni/AndroidRuntime.cpp
if (!SystemProperties.get("persist.sys.language").isEmpty()) {
final String languageTag = Locale.getDefault().toLanguageTag();
SystemProperties.set("persist.sys.locale", languageTag);
SystemProperties.set("persist.sys.language", "");
SystemProperties.set("persist.sys.country", "");
SystemProperties.set("persist.sys.localevar", "");
}
// The system server should never make non-oneway calls
Binder.setWarnOnBlocking(true);
// The system server should always load safe labels
PackageItemInfo.setForceSafeLabels(true);
// Deactivate SQLiteCompatibilityWalFlags until settings provider is initialized
SQLiteCompatibilityWalFlags.init(null);
// Here we go!
Slog.i(TAG, "Entered the Android system server!");
int uptimeMillis = (int) SystemClock.elapsedRealtime();
EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, uptimeMillis);
if (!mRuntimeRestart) {
MetricsLogger.histogram(null, "boot_system_server_init", uptimeMillis);
}
// In case the runtime switched since last boot (such as when
// the old runtime was removed in an OTA), set the system
// property so that it is in sync. We can | xq oqi't do this in
// libnativehelper's JniInvocation::Init code where we already
// had to fallback to a different runtime because it is
// running as root and we need to be the system user to set
// the property. http://b/11463182
SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
// Mmmmmm... more memory!
VMRuntime.getRuntime().clearGrowthLimit();
// The system server has to run all of the time, so it needs to be
// as efficient as possible with its memory usage.
VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
// Some devices rely on runtime fingerprint generation, so make sure
// we've defined it before booting further.
Build.ensureFingerprintProperty();
// Within the system server, it is an error to access Environment paths without
// explicitly specifying a user.
Environment.setUserRequired(true);
// Within the system server, any incoming Bundles should be defused
// to avoid throwing BadParcelableException.
BaseBundle.setShouldDefuse(true);
// Within the system server, when parceling exceptions, include the stack trace
Parcel.setStackTraceParceling(true);
// Ensure binder calls into the system always run at foreground priority.
BinderInternal.disableBackgroundScheduling(true);
// Increase the number of binder threads in system_server
BinderInternal.setMaxThreads(sMaxBinderThreads);
// Prepare the main looper thread (this thread).
android.os.Process.setThreadPriority(
android.os.Process.THREAD_PRIORITY_FOREGROUND);
android.os.Process.setCanSelfBackground(false);
Looper.prepareMainLooper();
Looper.getMainLooper().setSlowLogThresholdMs(
SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);
// Initialize native services.
System.loadLibrary("android_servers");
// Check whether we failed to shut down last time we tried.
// This call may not return.
performPendingShutdown();
// Initialize the system context.
// 首先创建了一个context
createSystemContext();
// Create the system service manager.
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setStartInfo(mRuntimeRestart,
mRuntimeStartElapsedTime, mRuntimeStartUptime);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
// Prepare the thread pool for init tasks that can be parallelized
SystemServerInitThreadPool.get();
} finally {
traceEnd(); // InitBeforeStartServices
}
// Start services.
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();
}
StrictMode.initVmDefaults(null);
if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
int uptimeMillis = (int) SystemClock.elapsedRealtime();
MetricsLogger.histogram(null, "boot_system_server_ready", uptimeMillis);
final int MAX_UPTIME_MILLIS = 60 * 1000;
if (uptimeMillis > MAX_UPTIME_MILLIS) {
Slog.wtf(SYSTEM_SERVER_TIMING_TAG,
"SystemServer init took too long. uptimeMillis=" + uptimeMillis);
}
}
// Loop forever.
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
在SystemServer启动过程中,首先创建了一个context,为什么首先创建了一个context呢,因为在接下来会创建服务进程,服务进程起来之后会引用到很多的资源文件,资源文件的引用就少不了上下文的使用,所以会首先创建一个系统的上下文。这一块也蛮重要的,给一副图:
紧接着就是启动了3种最重要的类型的服务,引导服务、核心服务、其他服务。这3种服务类型总共启动的服务数量有80多个,AMS服务就是在引导服务(startBootstrapServices())中去启动的。
// frameworks/base/services/java/com/android/server/SystemServer.java
/**
* Starts the small tangle of critical services that are needed to get
* the system off the ground. These services have complex mutual dependencies
* which is why we initialize them all in one place here. Unless your service
* is also entwined in these dependencies, it should be initialized in one of
* the other functions.
*/
private void startBootstrapServices() {
Slog.i(TAG, "Reading configuration...");
// 省略部分代码......
// Activity manager runs the show.
traceBeginAndSlog("StartActivityManager");
mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
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();
// 省略部分代码......
}
startBootstrapServices这个方法很长,只看跟AMS相关的流程。从上面的代码中可以得出,在System Server的启动过程中,会启动很多的服务,startBootstrapServices适用于启动引导服务的方法,在此方法中清晰的表明
AMS是通过SystemServiceManager.startService去启动的,参数是ActivityManagerService.Lifecycle.class,为什么引导服务(startBootstrapServices)启动的过程中会首先启动AMS服务呢?因为接下来启动的服务无论是核心服务或者其他服务时,有些服务是需要AMS服务来辅助完成的,所以AMS服务在整个服务启动过程中处于一个基础服务的属性,所以会首先启动AMS服务。
总结下来SystemServer的启动流程:
1.4 AMS(ActivityManagerService)的启动过程
上面的代码已经清晰地展示了AMS的启动是通过SystemServer的startServer方法传入ActivityManagerService.Lifecycle.class参数, 先看看startService方法:
// /frameworks/base/services/core/java/com/android/server/SystemServiceManager.java
final ActiveServices mServices;
/**
* Starts a service by class name.
*
* @return The service instance.
*/
@SuppressWarnings("unchecked")
public SystemService startService(String className) {
final Class<SystemService> serviceClass;
try {
serviceClass = (Class<SystemService>)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);
}
/**
* Creates and starts a system service. The class must be a subclass of
* {@link com.android.server.SystemService}.
*
* @param serviceClass A Java class that implements the SystemService interface.
* @return The service instance, never null.
* @throws RuntimeException if the service fails to start.
*/
@SuppressWarnings("unchecked")
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 {
// 通过反射拿到service class的内部类的Lifecycle类的构造方法,
// 然后通过构造方法创建对应的服务的内部类的Lifecycle的对象
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(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();
} catch (RuntimeException ex) {
throw new RuntimeException("Failed to start service " + service.getClass().getName()
+ ": onStart threw an exception", ex);
}
warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
}
startService方法很简单,是通过传进来的class然后反射创建对应的service的内部类Lifecycle类的对象服务。所以此处创建的是Lifecycle的实例, 之后startService方法会将创建的Lifecycle类的对象添加到对应的列表中,那么为什么要将创建的服务的Lifecycle保存起来呢?先看一下代码:
// frameworks/base/services/core/java/com/android/server/SystemServiceManager.java
/**
* Manages creating, starting, and other lifecycle events of
* {@link com.android.server.SystemService system services}.
*
* {@hide}
*/
public class SystemServiceManager {
private static final String TAG = "SystemServiceManager";
private static final int SERVICE_CALL_WARN_TIME_MS = 50;
private final Context mContext;
private boolean mSafeMode;
private boolean mRuntimeRestarted;
private long mRuntimeStartElapsedTime;
private long mRuntimeStartUptime;
// Services that should receive lifecycle events.
private final ArrayList<SystemService> mServices = new ArrayList<SystemService>();
// 省略代码......
}
其实目的就是将所有SystemServer启动的所有服务做统一的管理。最后startService通过已创建的Lifecycle类的对象调用start()方法(也就是真正的去创建服务对象AMS)。通过分析,可以看出SystemServerManager的startService方法其实就是一个框架代码,没有任何的具体业务相关的操作,只是通过传入的参数创建对应的服务对象,那startService为什么要做这么一个设计呢?因为这样设计的话,就相当于给AMS的启动过程有了生命周期,那对AMS来说这个ActivityManagerService.Lifecycle又是什么呢?先来看一下ActivityManagerService.Lifecycle:
// 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);
// 真正的创建ActivityManagerService对象
mService = new ActivityManagerService(context);
}
@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();
}
}
@Override
public void onCleanupUser(int userId) {
mService.mBatteryStatsService.onCleanupUser(userId);
}
public ActivityManagerService getService() {
return mService;
}
}
ActivityManagerService.Lifecycle继承自SystemService类,首先ActivityManagerService.Lifecycle这个类的构造方法中会创建ActivityManagerService对象。上面startService框架代码最后回调了ActivityManagerService.Lifecycle对象的onStart方法,也就是调用了ActivityManagerService的start方法。一步一步的来看,先来看看AMS的初始化做了什么操作。
ASM初始化(构造方法)
// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
// 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) {
LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
mInjector = new Injector();
mContext = systemContext;//赋值mContext
mFactoryTest = FactoryTest.getMode();
mSystemThread = ActivityThread.currentActivityThread();//获取当前的
ActivityThread mUiContext = mSystemThread.getSystemUiContext();//赋值mUiContext
Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
mPermissionReviewRequired = mContext.getResources().getBoolean(com.android.internal.R.bool.config_permissionReviewRequired);
//创建Handler线程,用来处理handler消息
mHandlerThread = new ServiceThread(TAG, THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
mHandlerThread.start();
mHandler = new MainHandler(mHandlerThread.getLooper());
mUiHandler = mInjector.getUiHandler(this);//处理ui相关msg的Handler
mProcStartHandlerThread = new ServiceThread(TAG + ":procStart", THREAD_PRIORITY_FOREGROUND, false /* allowIo */);
mProcStartHandlerThread.start();
mProcStartHandler = new Handler(mProcStartHandlerThread.getLooper());
//管理AMS的一些常量,厂商定制系统就可能修改此处
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());
}
//初始化管理前台、后台广播的队列, 系统会优先遍历发送前台广播
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;
//初始化管理Service的 ActiveServices对象
mServices = new ActiveServices(this);
mProviderMap = new ProviderMap(this);//初始化Provider的管理者
mAppErrors = new AppErrors(mUiContext, this);//初始化APP错误日志的打印器
//创建电池统计服务, 并输出到指定目录
File dataDir = Environment.getDataDirectory();
File systemDir = new File(dataDir, "system");
systemDir.mkdirs();
mAppWarnings = new AppWarnings(this, mUiContext, mHandler, mUiHandler,systemDir);
// TODO: Move creation of battery stats service outside of activity manager service.
mBatteryStatsService = new BatteryStatsService(systemContext, 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"));
mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);
//加载Uri的授权文件
mGrantFile = new AtomicFile(new File(systemDir, "urigrants.xml"), "urigrants");
//负责管理多用户
mUserController = new UserController(this);
//vr功能的控制器
mVrController = new VrController(this);
//初始化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;
}
mTrackingAssociations = "1".equals(SystemProperties.get("debug.trackassociations"));
mTempConfig.setToDefaults();
mTempConfig.setLocales(LocaleList.getDefault());
mConfigurationSeq = mTempConfig.seq = 1;
//管理ActivityStack的重要类,这里面记录着activity状态信息,是AMS中的核心类
mStackSupervisor = createStackSupervisor();
mStackSupervisor.onConfigurationChanged(mTempConfig);
//根据当前可见的Activity类型,控制Keyguard遮挡,关闭和转换。 Keyguard就是我们的锁屏相关页面
mKeyguardController = mStackSupervisor.getKeyguardController();
// 管理APK的兼容性配置 解析 / data / system / packages - compat.xml文件,该文件用于存储那些需要考虑屏幕尺寸的APK信 息,
mCompatModePackages = new CompatModePackages(this, systemDir, mHandler);
//Intent防火墙,Google定义了一组规则,来过滤intent,如果触发了,则intent会被系统丢弃,且不会告知发送者
mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
mTaskChangeNotificationController = new TaskChangeNotificationController(this, mStackSupervisor, mHandler);
//这是activity启动的处理类,这里管理者activity启动中用到的intent信息和flag标识,也和stack和task有重要的联系
mActivityStartController = new ActivityStartController(this);
mRecentTasks = createRecentTasks();
mStackSupervisor.setRecentTasks(mRecentTasks);
mLockTaskController = new LockTaskController(mContext, mStackSupervisor,mHandler);
// 在Android O(SDK28)之前是没有的,他主要就是用管理Activity的生命周期的
mLifecycleManager = new ClientLifecycleManager();
//启动一个线程专门跟进cpu当前状态信息,AMS对当前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);
}
}
}
};
mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext);
//看门狗,监听进程。这个类每分钟调用一次监视器。 如果进程没有任何返回就杀掉
Watchdog.getInstance().addMonitor(this);
Watchdog.getInstance().addThread(mHandler);
// bind background thread 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();
try {
Process.setThreadGroupAndCpuset(BackgroundThread.get().getThreadId(), Process.THREAD_GROUP_BG_NONINTERACTIVE);
} catch (Exception e) {
Slog.w(TAG, "Setting background thread cpuset failed");
}
}
AMS的onStart方法
// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
private void start() {
// 移除所有的进程组
removeAllProcessGroups();
// 启动CpuTracker线程
mProcessCpuThread.start();
// 启动电池统计服务
mBatteryStatsService.publish();
mAppOpsService.publish(mContext);
Slog.d("AppOps", "AppOpsService published");
// 创建LocalService,并添加到LocalServices
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.
//等待mProcessCpuThread完成初始化后, 释放锁,初始化期间禁止访问
try {
mProcessCpuInitLatch.await();
} catch (InterruptedException e) {
// 然后来看看setSystemProcess 干了什么事情
Slog.wtf(TAG, "Interrupted wait during start", e);
Thread.currentThread().interrupt();
throw new IllegalStateException("Interrupted wait during start");
}
}
看完AMS的构造方法和onStart方法之后,大概有个了解就可以。那么在启动引导服务(startBootstrapServices)的方法中,其实还有一个比较重要的操作:
那这个setSystemProcess做什么呢?
AMS的setSystemProcess
// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
public void setSystemProcess() {
try {
ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false,
DUMP_FLAG_PRIORITY_HIGH);
ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
ServiceManager.addService("dbinfo", new DbBinder(this));
if (MONITOR_CPU_USAGE) {
ServiceManager.addService("cpuinfo", new CpuBinder(this),
/* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
}
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);
}
// 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 (mAppOpsService.checkOperation(op, uid, packageName)
!= AppOpsManager.MODE_ALLOWED) {
runInBackgroundDisabled(uid);
}
}
}
});
}
注册大量服务。首先将ActivityManagerService注册到ServiceManager中,其次将几个与系统性能调试相关的服务注册到ServiceManager。这里的ServiceManger就是bindler的组成部分,与上面的SystemServerManager不是同一个东西哈。这里添加的这些服务,也就是adb shell dumsys 的各种服务的来源。
查询并处理ApplicationInfo。首先调用PackageManagerService的接口,查询包名为android的应用程 序的ApplicationInfo信息,对应于framework-res.apk。然后以该信息为参数调用ActivityThread上的installSystemApplicationInfo方法。
创建并处理ProcessRecord。调用ActivityManagerService上的newProcessRecordLocked,创建一个ProcessRecord类型的对象,并保存该对象的信息。
特别提一下,其中updateOomAdjLocked方法就是用来更新OomAdj的,OomAdj与手机杀进程有关系。若要进程保活,那就要对这个东西有一定的了解。
那再看一下ActivityManagerService.Lifecycle类中的onBootPhase方法,前面SystemServer启动过程中,也介绍了SystemServer的启动十分不同阶段,那怎么分的不同阶段呢?就是通过设置phase的值的时候,最终就会调用到onBootPhase(int phase)方法,那在这个方法中AMS会判定当前phase的值是否为系统服务完成状态,然后分别调用电池服务的systemServicesReady方法和AMS中ActiveServices 的systemServicesReady的方法。
// frameworks/base/services/core/java/com/android/server/SystemService.java
/**
* After receiving this boot phase, services can safely call into core system services
* such as the PowerManager or PackageManager.
*/
public static final int PHASE_SYSTEM_SERVICES_READY = 500;
// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
final ActiveServices mServices;
public static final class Lifecycle extends SystemService {
// 省略部分代码.....
@Override
public void onBootPhase(int phase) {
mService.mBootPhase = phase;
if (phase == PHASE_SYSTEM_SERVICES_READY) {
mService.mBatteryStatsService.systemServicesReady();
mService.mServices.systemServicesReady();
}
}
// 省略部分代码.....
}
那这个ActiveServices是个什么东西呢?其实AMS需要做的事情巨多,它需要管理4大组件,所以AMS将4大组件(activity\broadcast\service\provider)的管理内容分出去成立了单独的services,那Activity对应的services类就是ActiveServices,其他的3个组件也都有对应的services实现。
最后Lifecycle的getServer()方法就会将我们真正的AMS的对象返回出去:
// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
public static final class Lifecycle extends SystemService {
// 省略部分代码.....
public ActivityManagerService getService() {
return mService;
}
// 省略部分代码.....
}
那我们上面引导服务(startBootstrapServices())的方法中就会获取到真正的AMS对象:
mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();
到此处,我们的AMS就被创建并且执行起来了。
AMS启动总结
最后梳理一下整个AMS的启动过程:
当流程走到systemReady的时候,那就证明前面提到的到80多个服务已经初始化了。那接下来就会启动SystemUI进程(在startOtherServices方法中的mActivityManagerService.systemReady()方法中):
以及launcher进程:
// frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
// 省略部分代码......
if (goingCallback != null) goingCallback.run(); // 这里面会启动SystemUI
// 省略部分代码......
// 启动桌面...
startHomeActivityLocked(currentUserId, "systemReady");
// 省略部分代码......
}
那也就是说平时的SystemUI与Launcher都是AMS在systemReady方法中启动的进程。SystemUI的启动要早于Launcher的启动。那到此AMS的启动流程就完成了。
2 AMS相关重要类介绍
从第1章AMS启动完成突然间中间增加了本章节,有点突兀,但是为了能够更清晰的理解第3章startActivity的过程,所以在此处添加本章节,用于AMS中相关类的信息的介绍。本章节主要是介绍一些零散的知识点,只作为了解即可,没必要深究。如果不想了解,也可以直接跳过本章节,直接进入下一章第3章。
2.1 ProcessRecord 数据结构
第一类数据:描述身份的数据
- 1.ApplicationInfo info:AndroidManifest.xml中定义的Application信息
- 2.boolean isolated:是不是isolated进程
- 3.int uid:进程uid
- 4.int userId:这个是android做的多用户系统id,就像windows可以登录很多用户一样,android也希望可以实现类似的多用户
- 5.String processName:进程名字,默认情况下是包名
- 6.UidRecord uidRecord:记录已经使用的uid 7.IApplicationThread thread:这个很重要,它是ApplicationThread的客户端,AMS就是通过这 个对象给apk进程发送异步消息的(管理四大组件的消息),所以只有这个对象不为空的情况下, 才代表apk进程可是使用了
- 8.int pid:进程的pid 9.String procStatFile:proc目录下每一个进程都有一个以pid命名的目录文件,这个目录下记载着 进程的详细信息,这个目录及目录下的文件是内核创建的, proc是内核文件系统,proc就是
- process的缩写,涉及的目的就是导出进程内核信息
- 10.int[] gids:gid组
- 11.CompatibilityInfo compat : 兼容性信息
- 12.String requiredAbi : abi信息
- 13.String instructionSet : 指令集信息
第二类数据:描述进程中组件的数据
- 1.pkgList:进程中运行的包
- 2.ArraySet pkgDeps:进程运行依赖的包
- 3.ArrayList activities:进程启动的所有的activity组件记录表
- 4.ArraySet services:进程启动的所有的service组件记录表
- 5.ArraySet executingServices:正在运行(executing)是怎么定义的?首先需要明确的是系统是 怎么控制组件的?发送消息给apk进程,apk进程处理消息,上报消息完成,这被定义为一个完整 的执行过程,因此正在执行(executing)被定义为发送消息到上报完成这段时间
- 6.ArraySet connections:绑定service的客户端记录表
- 7.ArraySet receivers:广播接收器的记录表
- 8.ContentProviderRecord pubProviders:pub是publish(发布)的意思,ContentProvider需要 安装然后把自己发布到系统(AMS)中后,才能使用,安装指的是apk进程加载ContentProvider
- 子类、初始化、创建数据库等过程,发布是将ContentProvider的binder客户端注册到AMS中
- 9.ArrayList conProviders:使用ContentProvider的客户端记录表public class ActivityManagerService extends IActivityManager.Stub implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {}
- 10.BroadcastRecord curReceiver:当前进程正在执行的广播 在本节中以上组件信息只是做一个 简单的描述,以后单独分析组件管理的时候在详细介绍
第三类数据:描述进程状态的数据
- 1.int maxAdj:进程的adj上限(adjustment)
- 2.int curRawAdj:当前正在计算的adj,这个值有可能大于maxAdj 3.int setRawAdj:上次计算的curRawAdj设置到lowmemorykiller系统后的adj 4.int curAdj:当前正在计算的adj,这是curRawAdj被maxAdj削平的值
- 5.int setAdj:上次计算的curAdj设置到lowmemorykiller系统后的adj 6.int verifiedAdj:setAdj校验后的值
- 7.int curSchedGroup:正在计算的调度组
- 8.int setSchedGroup:保存上次计算的调度组
- 9.int curProcState:正在计算的进程状态
- 10.int repProcState:发送给apk进程的状态
- 11.int setProcState:保存上次计算的进程状态
- 12.int pssProcState:pss进程状态
- 13.ProcessState baseProcessTracker:进程状态监测器
- 14.int adjSeq:计算adj的序列数
- 15.int lruSeq:lru序列数
- 16.IBinder forcingToForeground:强制将进程的状态设置为前台运行的IBinder,IBinder代表的是 组件的ID,这个是整个android系统唯一
第四类数据:和pss相关的数据 我们先来普及一下一些名词:
VSS- Virtual Set Size 虚拟耗用内存(包含共享库占用的内存) RSS- Resident Set Size 实际使用 物理内存(包含共享库占用的内存) PSS- Proportional Set Size 实际使用的物理内存(比例分配 共享库占用的内存) USS- Unique Set Size 进