Android学习之路
https://www.cnblogs.com/fanglongxiang/p/13594986.html
系统启动, AMS起点前:
系统启动后Zygote进程第一个fork出SystemServer进程,进入到SystemServer:main()->run()->startBootstrapServices() 启动引导服务,进而完成AMS的启动
ZygoteInit.java:main()->forkSystemServer()->Zygote.java:forkSystemServer()->nativeForkSystemServer()->com_android_internal_os_Zygote.cpp:com_android_internal_os_Zygote_nativeForkSystemServer()->ZygoteInit.java->handleSystemServerProcess()
1. 为SystemServer进程创建Android运行环境,createSystemContext() -> new ActvityThread()-->attach ->getSystemContext ->createSystemContext
2. 启动AMS
3. 将SystemServer进程纳入到AMS的进程管理体系中
setSystemProcess()//将framewok-res.apk信息加入到SystemServer进程的LoadedApk中,构建SystemServe进程的ProcessRecord,保存到AMS中,以便AMS进程统一管理
installSystemProvider() //安装SystemServer进程中的SettingsProvider.apk
4. AMS启动完成,通知服务或应用完成后续工作,或直接启动新进程。
AMS.systemReady() // 许多服务或应用进程必须等待AMS完成启动工作后,才能启动或进行一些后续工作,AMS就是在SystemReady()中,通知或启动这些等待的服务和应用进程,例如启动桌面。等
几个重要的类:
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(); //启动其他服务,AMS启动后,完成后续桌面启动等操作
...
}
在SystemServer的run函数中,在启动AMS之前,调用了createSystemContext函,主要用来是初始化 System Context和SystemUi Context,并设置主题
调用createSystemContext 完毕后,完成以下内容
private void createSystemContext() {
ActivityThread activityThread = ActivityThread.systemMain(); //参考[4.2.1]
//获取system context
mSystemContext = activityThread.getSystemContext();
//设置系统主题
mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
//获取systemui context
final Context systemUiContext = activityThread.getSystemUiContext();
//设置systemUI 主题
systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
}
createSystemContext()创建了两个上下文,系统context和SystemUi context。这两个挺重要,会传入AMS中,这里就是它们创建的地方。
接下来看下上面创建两个上下文时的systemMain()
//ActivityThread.java
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对象
ActivityThread thread = new ActivityThread();
thread.attach(true, 0);
return thread;
}
ActivityThread是当前进程的主线程,SystemServer初始化时,ActivityThread.systemMain()创建的是系统进程SystemServer的主线程,因为SystemServer中也运行着一些系统APK,例如framewor-res.apk,SettingsProvider.apk,因此SystemServer也可以看作是一个特殊的应用进程。
AMS负责管理和调度进程,因此AMS需要通过Binder机制和应用进程通信,为此Android提供了一个IppliactionThread结构,该接口定义了AMS和应用进程之间的交互函数。
AcitityThread的构造函数比较简单,获取ResourceManager的单例对象,比较关键的是它的成员变量。
public final class ActivityThread extends ClientTransactionHandler {
...
//定义了AMS与应用通信的接口,拿到ApplicationThread的对象
final ApplicationThread mAppThread = new ApplicationThread();
//拥有自己的looper,说明ActivityThread确实可以代表事件处理线程
final Looper mLooper = Looper.myLooper();
//H继承Handler,ActivityThread中大量事件处理依赖此Handler
final H mH = new H();
//用于保存该进程的ActivityRecord
final ArrayMap<IBinder, ActivityClientRecord> mActivities = new ArrayMap<>();
//用于保存进程中的Service
final ArrayMap<IBinder, Service> mServices = new ArrayMap<>();
用于保存进程中的Application
final ArrayList<Application> mAllApplications
= new ArrayList<Application>();
//构造函数
@UnsupportedAppUsage
ActivityThread() {
mResourcesManager = ResourcesManager.getInstance();
}
}
对于系统进程而言,ActivityThread的attach函数最重要的工作,就是创建Instrumentation,Application和Context
attach(true,0) 这里走的是系统进程(应用启动也会走,system为false走的是应用进程),创建ActivityThread中的重要成员:Instrumentation、 Application 和 Context
private void attach(boolean system, long startSeq) {
mSystemThread = system;
//传入的system为0
if (!system) {
//应用进程的处理流程
...
} else {
//系统进程的处理流程,该情况只在SystemServer中处理
//创建ActivityThread中的重要成员:Instrumentation、 Application 和 Context
mInstrumentation = new Instrumentation();
mInstrumentation.basicInit(this);
//创建系统的Context,
ContextImpl context = ContextImpl.createAppContext(
this, getSystemContext().mPackageInfo);
//调用LoadedApk的makeApplication函数
mInitialApplication = context.mPackageInfo.makeApplication(true, null);
mInitialApplication.onCreate();
}
}
ContextImpl context = ContextImpl.createAppContext(this, getSystemContext().mPackageInfo);
这里创建的是一个LoadApk(packagenam是android,即framewor-res.apk),以此获取了Context对象mInitialApplication = context.mPackageInfo.makeApplication(true, null);
mInitialApplication.onCreate();
public ContextImpl getSystemContext() {
synchronized (this) {
if (mSystemContext == null) {
//调用ContextImpl的静态函数createSystemContext
mSystemContext = ContextImpl.createSystemContext(this);
}
return mSystemContext;
}
}
createSysteContext的内容就是创建一个LoadApk,然后初始化一个ContextImpl对象。创建的LoadApk对应的packageName为’‘android’,也就是framewok-res.apk.由于该APK仅供SystemServer进程,因此创建的Context被定义为System Context,现在该LoadApk还没有得到frame-res.apk实际信息。
当pkms启动,完成对应的解析后,ams将重新设置这个LoadedApk.
static ContextImpl createSystemContext(ActivityThread mainThread) {
//创建LoadedApk类,代表一个加载到系统中的APK
//注意此时的LoadedApk只是一个空壳
//PKMS还没有启动,无法得到有效的ApplicationInfo
LoadedApk packageInfo = new LoadedApk(mainThread);
//拿到ContextImpl 的对象
ContextImpl context = new ContextImpl(null, mainThread, packageInfo, null, null, null, 0,
null, null);
//初始化资源信息
context.setResources(packageInfo.getResources());
context.mResources.updateConfiguration(context.mResourcesManager.getConfiguration(),
context.mResourcesManager.getDisplayMetrics());
return context;
}
systemServiceManager对象主要用于管理SystemService的创建,启动等生命周期,SystemService类是一个抽象类。
在SystemServiceManager中都是通过反射创建SystemService对象的,而且在 startService(@NonNull final SystemService service) 方法中,会将 SystemService 添加到 mServices 中,并调用 onStart() 方法
private void run() {
...
//1.创建SystemServiceManager对象,参考 [4.3.1]
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setStartInfo(mRuntimeRestart,
mRuntimeStartElapsedTime, mRuntimeStartUptime);
//2.启动SystemServiceManager服务,参考[4.3.2]
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
...
}
public class SystemServiceManager {
...
private final Context mContext;
private final ArrayList<SystemService> mServices = new ArrayList<SystemService>();
...
SystemServiceManager(Context context) {
mContext = context;
}
public SystemService startService(String className) {
final Class<SystemService> serviceClass;
try {
//通过反射根据类名,拿到类对象
serviceClass = (Class<SystemService>)Class.forName(className);
} catch (ClassNotFoundException ex) {
Slog.i(TAG, "Starting " + className);
...
}
return startService(serviceClass);
}
public <T extends SystemService> T startService(Class<T> serviceClass) {
try {
final String name = serviceClass.getName();
// Create the service.
final T service;
...
service = constructor.newInstance(mContext);
...
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(); //调用各个服务中的onStart()方法完成服务启动
} catch (RuntimeException ex) {
throw new RuntimeException("Failed to start service " + service.getClass().getName()
+ ": onStart threw an exception", ex);
}
}
}
把SystemServiceManager的对象加入到本地服务的全局注册表中
public final class LocalServices {
private LocalServices() {}
private static final ArrayMap<Class<?>, Object> sLocalServiceObjects =
new ArrayMap<Class<?>, Object>();
//返回实现指定接口的本地服务实例对象
@SuppressWarnings("unchecked")
public static <T> T getService(Class<T> type) {
synchronized (sLocalServiceObjects) {
return (T) sLocalServiceObjects.get(type);
}
}
//将指定接口的服务实例添加到本地服务的全局注册表中
public static <T> void addService(Class<T> type, T service) {
synchronized (sLocalServiceObjects) {
if (sLocalServiceObjects.containsKey(type)) {
throw new IllegalStateException("Overriding service registration");
}
sLocalServiceObjects.put(type, service);
}
}
//删除服务实例,只能在测试中使用。
public static <T> void removeServiceForTest(Class<T> type) {
synchronized (sLocalServiceObjects) {
sLocalServiceObjects.remove(type);
}
}
}
private void run() {
...
//1.创建SystemServiceManager对象,参考 [4.3.1]
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setStartInfo(mRuntimeRestart,
mRuntimeStartElapsedTime, mRuntimeStartUptime);
//2.启动SystemServiceManager服务,参考[4.3.2]
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
...
}
private void startBootstrapServices() {
...
/*ActivityTaskManagerService是Android 10新引入的变化,也是系统服务,用来管理Activity启动和调度,包括其容器(task、stacks、displays等)。这篇主要关于AMS的启动,
Android 10将原先AMS中对activity的管理和调度移到了ActivityTaskManagerService中,
位置放到了wm下(见上面完整路径),
因此AMS负责四大组件中另外3个(service, broadcast, contentprovider)的管理和调度。*/
atm = mSystemServiceManager.startService(
ActivityTaskManagerService.Lifecycle.class).getService();
//启动服务 ActivityManagerService,简称AMS
//Lifecycle是AMS的内部类ActivityManagerService.Lifecycle.startService()最终返回的是mService,即创建的AMS对象。
mActivityManagerService = ActivityManagerService.Lifecycle.startService(
mSystemServiceManager, atm);
//安装Installer
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
//初始化PowerManager
mActivityManagerService.initPowerManagement();
//设置系统进程
mActivityManagerService.setSystemProcess();
}
private void startOtherServices() {
...
//安装SettingsProvider.apk
mActivityManagerService.installSystemProviders();
mActivityManagerService.setWindowManager(wm);
//AMS启动完成,完成后续的工作,例如启动桌面等
mActivityManagerService.systemReady(() -> {
...
}, BOOT_TIMINGS_TRACE_LOG);
...
}
//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();
// 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<T> constructor = serviceClass.getConstructor(Context.class);
service = constructor.newInstance(mContext);
} ......
startService(service);
return service;
}
}
public void startService(@NonNull final SystemService service) {
// Register it.
mServices.add(service);
// Start it.
long time = SystemClock.elapsedRealtime();
try {
service.onStart();
} catch (RuntimeException ex) {
......
}
warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
}
SystemServiceManager中通过反射,调用了ActivityManagerService.Lifecycle的构造方法,然后startService(service) 中最终调用了service.onStart(),即ActivityManagerService.Lifecycle.onStart()。
通过反射调用ActivityManagerService.Lifecycle的构造方法,主要new ActivityManagerService() 创建AMS对象,干了些什么需要了解;ActivityManagerService.Lifecycle.onStart()就是直接调用AMS的start()方法;
new ActivityManagerService()
// 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, ActivityTaskManagerService atm) {
LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
mInjector = new Injector();
//系统上下文,是在SystemServer进程fork出来后通过createSystemContext()创建的,即与SystemServer进程是一一致
mContext = systemContext;
mFactoryTest = FactoryTest.getMode();
//系统进程的主线程 sCurrentActivityThread,这里是systemMain()中创建的ActivityThread对象。即也与SystemServer一样的。
mSystemThread = ActivityThread.currentActivityThread();
mUiContext = mSystemThread.getSystemUiContext();
Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
mHandlerThread = new ServiceThread(TAG,
THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
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 /* allowIo */);
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);
// Broadcast policy parameters
final BroadcastConstants foreConstants = new BroadcastConstants(
Settings.Global.BROADCAST_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;
// by default, no "slow" policy in this queue
offloadConstants.SLOW_TIME = Integer.MAX_VALUE;
mEnableOffloadQueue = SystemProperties.getBoolean(
"persist.device_config.activity_manager_native_boot.offload_queue_enabled", false);
//创建几种广播相关对象,前台广播、后台广播、offload暂不了解TODO。
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();
// TODO: Move creation of battery stats service outside of activity manager service.
mBatteryStatsService = new BatteryStatsService(systemContext, systemDir,
BackgroundThread.get().getHandler());
mBatteryStatsService.getActiveStatistics().readLocked();
mBatteryStatsService.scheduleWriteToDisk();
mOnBattery = DEBUG_POWER ? true
: mBatteryStatsService.getActiveStatistics().getIsOnBattery();
mBatteryStatsService.getActiveStatistics().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);
// bind background threads 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(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的构造方法,主要完成一些对象的构造及变量的初始化,可以看下上面的注释。
AMS的start()
private void start() {
//移除所有的进程组
removeAllProcessGroups();
//启动CPU监控线程
mProcessCpuThread.start();
//注册电池、权限管理相关服务
mBatteryStatsService.publish();
mAppOpsService.publish(mContext);
Slog.d("AppOps", "AppOpsService published");
LocalServices.addService(ActivityManagerInternal.class, new LocalService());
mActivityTaskManager.onActivityManagerInternalAdded();
mUgmInternal.onActivityManagerInternalAdded();
mPendingIntentController.onActivityManagerInternalAdded();
// Wait for the synchronized block started in mProcessCpuThread,
// so that any other access 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");
}
}
//=============================================================================
ActivityManagerService.java:
public void setSystemServiceManager(SystemServiceManager mgr) {
mSystemServiceManager = mgr;
}
//=============================================================================
ActivityManagerService.java:
public void setInstaller(Installer installer) {
mInstaller = installer;
}
//=============================================================================
ActivityManagerService.java:
public void initPowerManagement() {
mActivityTaskManager.onInitPowerManagement();
mBatteryStatsService.initPowerManagement();
mLocalPowerManager = LocalServices.getService(PowerManagerInternal.class);
}
//=============================================================================
public void setSystemProcess() {
try {
//注册服务activity
ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ 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), /* allowIsolated= */ 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),
/* allowIsolated= */ 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.installSystemApplicationInfo(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.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);
}
}
}
});
}
上面讲到的都是startBootstrapServices(),AMS的启动在其中。最后,当引导服务、核心服务、其他服务都完成后,会调用AMS中的systemReady()方法。
总结: