Android AMS startup details
- 2021-12-11 19:04:36
- OfStack
start()
setSystemProcess
Follow-up goingCallBackstartHomeOnAllDisplays Summary:
Start
As we mentioned in the Android system startup process, AMS is started in system_service,
//frameworks/base/services/java/corri/android/server/SystemServer.java
// This method mainly starts the service ActivityManagerService , PowerManagerService , LightsService , DisplayManagerService , PackageManagerService , UserManagerService .
// Settings ActivityManagerService To start the sensor service.
startBootstrapServices(); // Start the boot service
// The method mainly
// Startup service BatteryService Used to count battery power, which requires LightService .
// Startup service UsageStatsService Used to count application usage.
// Startup service WebViewUpdateService .
startCoreServices(); // Start core services
// This method mainly starts the service InputManagerService , WindowManagerService .
// Wait ServiceManager , SurfaceFlinger Startup is completed, and then the startup interface is displayed.
// Startup service StatusBarManagerService ,
// Get ready window, power, package, display Services:
// - WindowManagerService.systemReady()
// - PowerManagerService.systemReady()
// - PackageManagerService.systemReady()
// - DisplayManagerService.systemReady()
startOtherServices(); // Start other services
In starting the core service function, AMS will be started.
//frameworks/base/services/java/corri/android/server/SystemServer.java
private void startBootstrapServices() {
...
// Here will be ATMS Register to ServiceManager And then call the ATMS Adj. start Method.
ActivityTaskManagerService atm = mSystemServiceManager.startService(ActivityTaskManagerService.Lifecycle.class).getService();
// Emphasis method 1 . Registration AMS Service and returns the corresponding object information
mActivityManagerService = ActivityManagerService.Lifecycle.startService(mSystemServiceManager, atm);
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
// Settings app Installer
mActivityManagerService.setInstaller(installer);
...
// Emphasis method 2 . Toward ServiceManager Register in Binder Services
mActivityManagerService.setSystemProcess();
}
Here we only intercepted the startup code of AMS.
Here, the AMS registration and startup process will be carried out through the startService method. Let's look at the startService method in the specific ActivityManagerService
startService
//
public static ActivityManagerService startService(SystemServiceManager ssm, ActivityTaskManagerService atm) {
sAtm = atm;
// Call SM Adj. startService Method. Create AMS Instance and start the AMS
return ssm.startService(ActivityManagerService.Lifecycle.class).getService();
}
As we explained in how ServiceManager works, the systemServiceManager. startService method registers the corresponding service in ServiceManager and then calls the start method.
//frameworks/base/services/core/java/com/android/server/SystemServiceManager.java
public SystemService startService(String className) {
final Class<SystemService> serviceClass;
serviceClass = (Class<SystemService>)Class.forName(className);
return startService(serviceClass);
}
@SuppressWarnings("unchecked")
public <T extends SystemService> T startService(Class<T> serviceClass) {
try {
final String name = serviceClass.getName();
final T service;
try {
// Reflection constructor
Constructor<T> constructor = serviceClass.getConstructor(Context.class);
// Create a service
service = constructor.newInstance(mContext);
...
// Startup service
startService(service);
return service;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
}
public void startService(@NonNull final SystemService service) {
// Register it.
// Register to ServiceManager In the list
mServices.add(service);
// Invoke the corresponding of the service onStart Method
service.onStart();
}
The parameter passed in when starting AMS is: ActivityManagerService. Lifecycle. class. So you actually call the constructor of ActivityManagerService. Lifecycle, and then call its onStart method
public static final class Lifecycle extends SystemService {
private final ActivityTaskManagerService mService;
public Lifecycle(Context context) {
super(context);
// Create AMS Object
mService = new ActivityManagerService(context, sAtm);
}
@Override
public void onStart() {
// Call AMS Adj. start Method
mService.start();
}
public ActivityManagerService getService() {
// Returned AMS Instances
return mService;
}
}
During the creation of the Lifecycle object, the AMS object is created and then started with the start () method.
Creation of AMS
The AMS object is created through the constructor.
// Construction method,
public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
// Object of the system ActivityThread
mSystemThread = ActivityThread.currentActivityThread();
// Create 1 A ServiceThread Used to deal with AMS Commands received
mHandlerThread = new ServiceThread(TAG,THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
mHandlerThread.start();
mHandler = new MainHandler(mHandlerThread.getLooper());
mUiHandler = mInjector.getUiHandler(this);
// Low memory monitoring
mLowMemDetector = new LowMemDetector(this);
// Initializes the broadcast queue. It includes foreground broadcast, background broadcast and so on
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;
// Used to save the registration Service
mServices = new ActiveServices(this);
//map That is used to save the registered ContentProvider
mProviderMap = new ProviderMap(this);
mPackageWatchdog = PackageWatchdog.getInstance(mUiContext);
mAppErrors = new AppErrors(mUiContext, this, mPackageWatchdog);
// Create /data/system Directory
final File systemDir = SystemServiceManager.ensureSystemDir();
// Create a process statistics service and save it in the /data/system/proccstats In the directory.
mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
// Assignment ATM And initialize
mActivityTaskManager = atm;
mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController, DisplayThread.get().getLooper());
//CPU Tracker process
mProcessCpuThread = new Thread("CpuTracker") {
@Override
public void run() {
...
}
};
}
In the constructor of AMS, some initialization things are carried out: for example, starting CPU monitoring, starting process statistics service, starting low memory monitoring, initializing Service and ContentProvider corresponding save classes, etc.
start()
When the AMS class is created, the start () method is called.
private void start() {
// Remove all process groups
removeAllProcessGroups();
// Start CpuTracker Thread
mProcessCpuThread.start();
// Start the battery statistics service, which can count the battery consumption of specific applications, so as to proceed 1 Constant electricity statistics
mBatteryStatsService.publish();
// Create LocalService And add to the LocalServices In the list
LocalServices.addService(ActivityManagerInternal.class, new LocalService());
mActivityTaskManager.onActivityManagerInternalAdded();
mUgmInternal.onActivityManagerInternalAdded();
mPendingIntentController.onActivityManagerInternalAdded();
}
In the start method, 1 threads created in the constructor are started.
setSystemProcess
After creation and startup is complete, a number of system-related services are registered with ServiceManager through the setSystemProcess method.
public void setSystemProcess() {
try {
// Registration ActivityService Services
ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
// Register Process State Service
ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
// Registered memory Binder
ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false,DUMP_FLAG_PRIORITY_HIGH);
// Register image Binder
ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
// Registration SQLite DB binder
ServiceManager.addService("dbinfo", new DbBinder(this));
if (MONITOR_CPU_USAGE) {
// Registration CPU Usage of Binder
ServiceManager.addService("cpuinfo", new CpuBinder(this),/* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
}
// Registration authority control Binder
ServiceManager.addService("permission", new PermissionController(this));
// Registration process management Binder
ServiceManager.addService("processinfo", new ProcessInfoService(this));
// Get " android "Applied ApplicationInfo And loaded into the mSystemThread
ApplicationInfo info = mContext.getPackageManager().getApplicationInfo("android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
// Create ProcessRecord Maintain information about the process
synchronized (this) {
ProcessRecord app = mProcessList.newProcessRecordLocked(info, info.processName,...);
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);
}
}
In this method, 1 system process will be set, and the main functions are:
Register one service: activity, procstats, meminfo, gfxinfo, dbinfo, cpuinfo, permission, processinfo, etc. Get the ApplicationInfo object of the application whose package name is "android", and install and set the ApplicationInfo information to SystemThread (the main thread of the system process). That is to say, it can be understood that the system is also a special application. Creating an ProcessRecord maintains information about the process, where MY_PID is the SystemServer process ID. Start the detection application running and interacting.
Follow-up
After AMS is created and started, there will be 1 series of follow-up work to be done. These operations are called in **startOtherServices () **
private void startOtherServices() {
// Of the registration system ContentProvider Information
mActivityManagerService.installSystemProviders();
mActivityManagerService.setWindowManager(wm);
mActivityManagerService.systemReady(() -> {
......//goingCallback
}, BOOT_TIMINGS_TRACE_LOG);
}
The main functions here are:
Critical services continue to initialize Processes that have been started will be dropped by kill if they do not have the FLAG_PERSISTENT flag bit Run goingCallBack Start Activity of launcher, that is, desktop application.Here, continue to track the specific implementation content of goingCallBack under 1.
goingCallBack
mActivityManagerService.systemReady(() -> {
try {
// Start NativeCrash Monitoring of
mActivityManagerService.startObservingNativeCrashes();
} catch (Throwable e) {
reportWtf("observing native crashes", e);
}
if (!mOnlyCore && mWebViewUpdateService != null) {
webviewPrep = SystemServerInitThreadPool.get().submit(() -> {
// Start WebView Correlation
mWebViewUpdateService.prepareWebViewInSystemServer();
}, WEBVIEW_PREPARATION);
}
try {
// Start systemUI
startSystemUi(context, windowManagerF);
} catch (Throwable e) {
reportWtf("starting System UI", e);
}
...
}
In this one, I will continue to do some initialization work:
Start NativeCrash monitoring Start WebView related services Start SystemUI
startHomeOnAllDisplays
This function is mainly to start the desktop program, and the start-up process of AMS is not related, so it will not be analyzed in detail here.
Summary:
AMS is created and started in the SystemServer process
In the process of service startup of AMS, a number of objects are created and initialized by constructor (the list and scheduling objects of other three components except Activity are created; Memory, battery, authority, monitoring of CPU and other related objects are created), and the service is started by start () method (removing process group, starting CPU thread, authority registration, battery service and so on).
After AMS is created and the corresponding service is started, the information of framework-res. apk is added to LoadedApk of SystemServer process by setSystemProcess method, and ProcessRecord of SystemServer process is created, added to mPidsSelfLocked, and handed over to AMS for unified management
Subsequent work after AMS is started is mainly performed by calling systemReady () and the incoming goingCallBack. Mainly a variety of services or processes, such as AMS startup after the completion of the need to step 1 to complete the work and system-related initialization.
The desktop application is started in the systemReady () method, and systemUI is completed in goingCallback.
When the desktop application is started, the boot broadcast ACTION_BOOT_COMPLETED is sent.
The above is Android AMS startup details, more about Android AMS startup information please pay attention to other related articles on this site!