1.AMS/ATMS
在android10之前,android的四大组件统一由AMS进行管理;在android10之后,ATMS负责activity的相关管理,剩下的三大组件还是由AMS管理,不过在AMS中持有ATMS。同时,AMS也对进程、电池、内存、权限等进行管理。
注:AMS、ATMS服务都是在系统进程system server进程中。
AMS相关目录的几个重要文件:
①frameworks/base/core/java/android/app/下:
Activity.java:所有Activity的父类。
ActivityManager.java:AMS的客户端,提供给用户可调用的api。
ActivityThread.java:应用进程的主线程类,一般即UI线程。
②frameworks/base/services/core/java/com/android/server/am/下:
ActiveServices.java:控制service的启动、重启等。
ProcessRecord.java:记录每个进程的信息。
③frameworks/base/services/core/java/com/android/server/wm/下:
ActivityRecord.java:activity对象信息的记录。
ActivityStack.java/ActivityStackSupervisor.java:管理activity生命周期及堆栈等。
TaskRecord.java:任务栈记录,管理一个任务的应用activity。
ActivityTaskManagerService.java/ActivityTaskManagerInternal.java:管理activity的启动和调度。
2.AMS的启动流程
ActivityManagerService是在SystemServer.java中启动的。系统启动后Zygote进程第一个fork出SystemServer进程:
然后,进入到SystemServer:main()->run()->startBootstrapServices() 启动引导服务,在引导服务中完成AMS的启动。
在SystemServer中,会按顺序依次启动各个服务:
SystemServer.java:
public static void main(String[] args) {
new SystemServer().run();
}
private void run() {
...
//1.初始化 System Context
createSystemContext();
//2.创建 SystemServiceManager对象,主要用来管理SystemService的创建和启动等生命周期
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setStartInfo( mRuntimeRestart, mRuntimeStartElapsedTime, mRuntimeStartUptime);
LocalServices.addService( SystemServiceManager.class, mSystemServiceManager);
...
//3.启动服务
startBootstrapServices(); //启动引导服务,在其中启动了ATM和AMS服务,通过AMS安装Installer、初始化Power,设置系统进程等
startCoreServices(); //启动核心服务
startOtherServices(); //启动其他服务
}
在SystemServer的run函数中,启动AMS之前,调用了createSystemContext函数,主要用来初始化System Context和SystemUi Context,并设置主题:
private void createSystemContext() {
ActivityThread activityThread = ActivityThread.systemMain();
//获取system context
mSystemContext = activityThread.getSystemContext();
//设置系统主题
mSystemContext.setTheme( DEFAULT_SYSTEM_THEME);
//获取systemui context
final Context systemUiContext = activityThread.getSystemUiContext();
//设置systemUI 主题
systemUiContext.setTheme( DEFAULT_SYSTEM_THEME);
}
调用createSystemContext主要完成两件事情:
①得到一个ActivityThread对象,代表当前进程(此时为系统进程)的主线程
②得到一个Context对象,对SystemServer而言,它包含的application运行环境与framewokr-res.apk有关。
createSystemContext()创建了两个上下文,系统context和SystemUi context。这两个挺重要,会传入AMS中,这里就是它们创建的地方。
ActivityThread是当前进程的主线程。SystemServer初始化时ActivityThread.systemMain()创建的是系统进程(SystemServer进程)的主线程。
AMS、ATM都是在startBootstrapServices函数里启动的,WMS是在startOtherServices函数里启动的。
跟踪startBootstrapServices函数:
frameworks/base/services/java/com/android/server/SystemServer.java:
private void startBootstrapServices() {
.....
//创建ATM对象,并调用它的start方法
ActivityTaskManagerService atm = mSystemServiceManager.startService(ActivityTaskManagerService.Lifecycle.class).getService();
//创建AMS对象,并调用它的start方法(AMS中持有ATM的引用)
mActivityManagerService = ActivityManagerService.Lifecycle.startService( mSystemServiceManager, atm);
mActivityManagerService.setSystemServic eManager(mSystemServiceManager);
mActivityManagerService.setInstaller( installer);
mActivityManagerService.initPowerManagem ent();
mActivityManagerService.setSystemProcess();
watchdog.init(mSystemContext, mActivityManagerService);
}
(1)mSystemServiceManager.startService(ActivityTaskManagerService.Lifecycle.class).getService()和ActivityManagerService.Lifecycle.startService()里执行过程是一样的,这句创建了ActivityTaskManagerService对象,并调用了ActivityTaskManagerService中的start()方法启动服务。
ActivityTaskManagerService是Android 10新引入的变化,也是系统服务,用来管理Activity启动和调度,包括其容器(task、stacks、displays等)。
Android 10将原先AMS中对activity的管理和调度移到了ActivityTaskManagerService中,因此AMS负责四大组件中另外3个(service, broadcast, contentprovider)的管理和调度。
然后看ActivityManagerService.Lifecycle.class类,在ActivityManagerService 中:
ActivityManagerService.java
public static final class Lifecycle extends SystemService {
private final ActivityManagerService mService;
private static ActivityTaskManagerService sAtm;
public Lifecycle(Context context) {
super(context);
mService = new ActivityManagerService( context, sAtm);
}
public static ActivityManagerService startService(SystemServiceManager ssm, ActivityTaskManagerService atm) {
sAtm = atm;
return ssm.startService( ActivityManagerService.Lifecycle.class).getService();
}
@Override
public void onStart() {
mService.start();
}
public ActivityManagerService getService() {
return mService;
}
这里的Lifecycle是AMS的内部类。ActivityManagerService.Lifecycle.startService()最终返回的是mService,即创建的AMS对象。
接着来具体看下这个过程的实现,ActivityManagerService.Lifecycle.startService()进入SystemServiceManager类的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();
if (!SystemService.class.isAssignableFrom( serviceClass)) {
throw new RuntimeException("Failed to create " + name + ": service must extend " + SystemService.class.getName());
}
final T service;
try {
Constructor<T> constructor = serviceClass.getConstructor(Context.class);
service = constructor.newInstance( mContext);
}
startService(service);
return service;
}
}
public void startService(final SystemService service) {
mServices.add(service); // Register it.
// Start it.
long time = SystemClock.elapsedRealtime();
try {
service.onStart();
} catch (RuntimeException ex) {
......
}
warnIfTooLong(SystemClock.elapsedRealtim e() - time, service, "onStart");
}
SystemServiceManager中通过反射,调用了ActivityManagerService.Lifecycle的构造方法,然后startService(service) 中最终调用了service.onStart(),即ActivityManagerService.Lifecycle.onStart(),这样就把ActivityManagerService创建了。
接着需要看两点:通过反射调用ActivityManagerService.Lifecycle的构造方法,主要new ActivityManagerService() 创建AMS对象,干了些什么需要了解;ActivityManagerService.Lifecycle.onStart()就是直接调用AMS的start()方法;
①new ActivityManagerService()
public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
//系统上下文,是在SystemServer进程fork出来后通过createSystemContext()创建的,即与SystemServer进程是一一致
mContext = systemContext;
//系统进程的主线程 sCurrentActivityThread,这里是systemMain()中创建的ActivityThread对象。即也与SystemServer一样的。
mSystemThread = ActivityThread.currentActivityThread();
mUiContext = mSystemThread.getSystemUiContext();
mHandlerThread = new ServiceThread(TAG, THREAD_PRIORITY_FOREGROUND, false);
mHandlerThread.start();
//处理AMS消息的handle
mHandler = new MainHandler( mHandlerThread.getLooper());
//UiHandler对应于Android中的Ui线程
mUiHandler = mInjector.getUiHandler(this);
mProcStartHandlerThread = new ServiceThread(TAG + ":procStart", THREAD_PRIORITY_FOREGROUND, false);
mProcStartHandlerThread.start();
mProcStartHandler = new Handler( mProcStartHandlerThread.getLooper());
mConstants = new ActivityManagerConstants( mContext, this, mHandler);
final ActiveUids activeUids = new ActiveUids(this, true /* postChangesToAtm */);
mProcessList.init(this, activeUids);
mLowMemDetector = new LowMemDetector(this);
mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids);
final BroadcastConstants foreConstants = new BroadcastConstants(Settings.Global.BROAD CAST_FG_CONSTANTS);
foreConstants.TIMEOUT = BROADCAST_FG_TIMEOUT;//10s
final BroadcastConstants backConstants = new BroadcastConstants( Settings.Global.BROADCAST_BG_CONSTANTS);
backConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;//60s
final BroadcastConstants offloadConstants = new BroadcastConstants( Settings.Global.BROADCAST_OFFLOAD_CONSTANTS);
offloadConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
offloadConstants.SLOW_TIME = Integer.MAX_VALUE;
mEnableOffloadQueue = SystemProperties.getBoolean("persist.device_config.activity_manager_native_boot.offload_queue_enabled", false);
//创建几种广播相关对象,前台广播、后台广播
mFgBroadcastQueue = new BroadcastQueue(this, mHandler,"foreground", foreConstants, false);
mBgBroadcastQueue = new BroadcastQueue(this, mHandler,"background", backConstants, true);
mOffloadBroadcastQueue = new BroadcastQueue(this, mHandler,"offload", offloadConstants, true);
mBroadcastQueues[0] = mFgBroadcastQueue;
mBroadcastQueues[1] = mBgBroadcastQueue;
mBroadcastQueues[2] = mOffloadBroadcastQueue;
// 创建ActiveServices对象,管理 ServiceRecord
mServices = new ActiveServices(this);
// 创建ProviderMap对象,管理ContentProviderRecord
mProviderMap = new ProviderMap(this);
mPackageWatchdog = PackageWatchdog.getInstance(mUiContext);
mAppErrors = new AppErrors(mUiContext, this, mPackageWatchdog);
final File systemDir = SystemServiceManager.ensureSystemDir();
mBatteryStatsService = new BatteryStatsService(systemContext, systemDir, BackgroundThread.get().getHandler());
mBatteryStatsService.getActiveStatisti cs().readLocked();
mBatteryStatsService.scheduleWriteToDisk();
mOnBattery = DEBUG_POWER ? true : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
mBatteryStatsService.getActiveStatistic s().setCallback(this);
mOomAdjProfiler.batteryPowerChanged( mOnBattery);
mProcessStats = new ProcessStatsService( this, new File(systemDir, "procstats"));
mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);
mUgmInternal = LocalServices.getService( UriGrantsManagerInternal.class);
mUserController = new UserController(this);
mPendingIntentController = new PendingIntentController(mHandlerThread.getLooper(), mUserController);
if (SystemProperties.getInt("sys.use_fifo_ui", 0) != 0) {
mUseFifoUiScheduling = true;
}
mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
//得到ActivityTaskManagerService的对象,调用ATM.initialize
mActivityTaskManager = atm;
mActivityTaskManager.initialize( mIntentFirewall, mPendingIntentController, DisplayThread.get().getLooper());
mAtmInternal = LocalServices.getService( ActivityTaskManagerInternal.class);
mProcessCpuThread = new Thread("CpuTracker") {
......
};
mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext);
//加入Watchdog的监控
Watchdog.getInstance().addMonitor(this);
Watchdog.getInstance().addThread( mHandler);
updateOomAdjLocked( OomAdjuster.OOM_ADJ_REASON_NONE);
try {
Process.setThreadGroupAndCpuset( BackgroundThread.get().getThreadId(),Process.THREAD_GROUP_SYSTEM);
Process.setThreadGroupAndCpuset( mOomAdjuster.mAppCompact.mCompactionThread.getThreadId(),Process.THREAD_GROUP_SYSTEM);
} catch (Exception e) {
Slog.w(TAG, "Setting background thread cpuset failed");
}
}
AMS的构造方法,主要完成一些对象的构造及变量的初始化。
三大组件的(service、broadcast、provider)管理和调度(activity移到了ActivityTaskManagerService中,但此处也绑定了ActivityTaskManagerService对象)。
监控内存、电池、权限以及性能相关的对象或变量。mLowMemDetector、mBatteryStatsService、mProcessStats、mAppOpsService、mProcessCpuThread等。
②AMS的start()
private void start() {
removeAllProcessGroups(); //移除所有进程组
mProcessCpuThread.start(); //启动CPU监控线程
//注册电池、权限管理相关服务
mBatteryStatsService.publish();
mAppOpsService.publish(mContext);
LocalServices.addService( ActivityManagerInternal.class, new LocalService());
mActivityTaskManager.onActivityManag erInternalAdded();
mUgmInternal.onActivityManagerIntern alAdded();
mPendingIntentController.onActivityMan agerInternalAdded();
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()主要:
移除所有进程组,复位进程后,启动CPU监控线程。mProcessCpuThread在前面构造函数中创建的线程。
注册电池、权限管理的相关服务
LocalService只能本进程使用,不可跨进程。
(2)mActivityManagerService.setSystemServiceManager(mSystemServiceManager)
ActivityManagerService.java:
public void setSystemServiceManager( SystemServiceManager mgr) {
mSystemServiceManager = mgr;
}
很简单,将SystemServer.java中创建的SystemServiceManager对象mSystemServiceManager设置到了AMS中。
(3)mActivityManagerService.setInstaller(installer)
ActivityManagerService.java:
public void setInstaller(Installer installer) {
mInstaller = installer;
}
同样,将SystemServer.java中创建的Installer对象installer设置到AMS中。
(4)mActivityManagerService.initPowerManagement()
ActivityManagerService.java:
public void initPowerManagement() {
mActivityTaskManager.onInitPowerManage ment();
mBatteryStatsService.initPowerManageme nt();
mLocalPowerManager = LocalServices.getService(PowerManagerInternal.class);
}
在前面创建AMS过程,mActivityTaskManager、mBatteryStatsService对象已创建 相关服务已注册。这里初始化电源管理的功能。
(5)mActivityManagerService.setSystemProcess()
public void setSystemProcess() {
try {
//注册服务activity
ServiceManager.addService( Context.ACTIVITY_SERVICE, this, true, DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
//注册服务procstats,进程状态
ServiceManager.addService( ProcessStats.SERVICE_NAME, mProcessStats);
//注册服务meminfo,内存信息
ServiceManager.addService("meminfo", new MemBinder(this), false, DUMP_FLAG_PRIORITY_HIGH);
//注册服务gfxinfo,图像信息
ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
//注册服务dbinfo,数据库信息
ServiceManager.addService("dbinfo", new DbBinder(this));
if (MONITOR_CPU_USAGE) {
//注册服务cpuinfo,cpu信息
ServiceManager.addService("cpuinfo", new CpuBinder(this), false, DUMP_FLAG_PRIORITY_CRITICAL);
}
//注册服务permission和processinfo,权限和进程信息
ServiceManager.addService("permission", new PermissionController(this));
ServiceManager.addService("processinfo", new ProcessInfoService(this));
//获取“android”应用的ApplicationInfo,并装载到mSystemThread
ApplicationInfo info = mContext.getPackageManager().getApplicationInfo("android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
mSystemThread.installSystemApplica tionInfo(info, getClass().getClassLoader());
//创建ProcessRecord维护进程的相关信息
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);
}
} catch (PackageManager.NameNotFoundExc eption e) {
throw new RuntimeException( "Unable to find android system package", e);
}
}
这个方法设置系统进程,AMS的setSystemProcess主要:
注册一些服务:activity、procstats、meminfo、gfxinfo、dbinfo、cpuinfo、permission、processinfo;
这里获取包名为“android”的应用的ApplicationInfo对象,并将该ApplicationInfo信息安装设置到SystemThread(系统进程主线程)。即可以理解,系统也是一个特殊的应用。
创建ProcessRecord维护进程的相关信息,这里MY_PID即为SystemServer进程ID。
启动 检测应用运行和交互。
(6)watchdog.init(mSystemContext, mActivityManagerService)
初始化看门狗,AMS实列作为参数设置进入。
大致总结下AMS的启动:
①系统启动后Zygote进程第一个fork出SystemServer进程
②SystemServer->run()->createSystemContext():创建了系统的ActivityThread对象,运行环境mSystemContext、systemUiContext。
③SystemServer->run()->startBootstrapServices()->ActivityManagerService.Lifecycle.startService():AMS在引导服务启动方法中,通过构造函数new ActivityManagerService()进行了一些对象创建和初始化(除activity外3大组件的管理和调度对象创建;内存、电池、权限、性能、cpu等的监控等相关对象创建),start()启动服务(移除进程组、启动cpu线程、注册权限、电池等服务)。
④SystemServer->run()->startBootstrapServices()->setSystemServiceManager()、setInstaller()、initPowerManagement()、setSystemProcess():AMS创建后进行了一系列相关的初始化和设置。
setSystemProcess():将framework-res.apk的信息加入到SystemServer进程的LoadedApk中,并创建了SystemServer进程的ProcessRecord,加入到mPidsSelfLocked,由AMS统一管理。
⑤SystemServer->run()->startOtherServices():AMS启动后的后续工作,主要调用systemReady()和运行调用时传入的goingCallback。
systemReady()/goingCallback:各种服务或进程等AMS启动完成后需进一步完成的工作及系统相关初始化。 桌面应用在systemReady()方法中启动,systemui在goingCallback中完成。当桌面应用启动完成后,发送开机广播ACTION_BOOT_COMPLETED。