This is the ninth day of my participation in the First Challenge 2022. For details: First Challenge 2022.
ActivityManagerService Startup process analysis
ActivityManagerService is one of the core services of system services, and is closely related to the startup, lifecycle, and scheduling of the four components.
As we all know, the init process forks a Zygote process to start a Java world in which the SystemServer class loads the Java world services and properties. This is where the startup process for the ActivityManagerService we will examine today starts
After the SystemServer service is started, a startBootstrapServices function is called in its run function, which starts the ActivityManagerService service that is the hero of today
SystemServer.java
/ / 1. Initialize a ActivityTaskManagerService object
ActivityTaskManagerService atm = mSystemServiceManager.startService(
ActivityTaskManagerService.Lifecycle.class).getService();
// 2. Initialize ActivityManagerServive objects
mActivityManagerService = ActivityManagerService.Lifecycle.startService(
mSystemServiceManager, atm);
// Set SystemServiceManager and Installer
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
ActivityManagerService.java
public void setSystemServiceManager(SystemServiceManager mgr) {
mSystemServiceManager = mgr;
}
public void setInstaller(Installer installer) {
mInstaller = installer;
}
Copy the code
Let’s analyze the process step by step
ActivityTaskManagerService object initialization
From the foregoing we have instructions in the article SystemServiceManager startService function analysis, SystemServiceManager. StartService function mainly has three steps
- Initialize the corresponding SystemService and call its single-parameter constructor that takes the Context object as an argument, passing it the Context object created by createSystemContext in SystemServer
- The incoming parameters SystemService object is added to the SystemServiceManager. MServices saved, mServices is a SystemService object of ArrayList object
- Call the onStart function of the passed parameter SystemService object
So, let’s take a look
ActivityTaskManagerService. The Lifecycle of the single (Context) constructor calls refs
public Lifecycle(Context context) {
super(context);
mService = new ActivityTaskManagerService(context);
}
public ActivityTaskManagerService(Context context) {
mContext = context;
mFactoryTest = FactoryTest.getMode();
/ / this function will return a ActivityThread object, the object in the SystemServer. CreateSystemContext function call
// initialized via the ActivityThread constructor
mSystemThread = ActivityThread.currentActivityThread();
/ / get ActivityThread mSystemUiContext parameters, it is a ContextImpl object
mUiContext = mSystemThread.getSystemUiContext();
// Initialize a ClientLifecycleManager object
// This object manages all client lifecycles, callback functions, etc
mLifecycleManager = new ClientLifecycleManager();
/ / LocalService inherited from ActivityTaskManagerInternal class
mInternal = new LocalService();
GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
// Control the class that the view displays
mWindowOrganizerController = new WindowOrganizerController(this);
mTaskOrganizerController = mWindowOrganizerController.mTaskOrganizerController;
}
Copy the code
Let’s take a look at the class diagram
classDiagram
ActivityTaskManagerService o-- Context
ActivityTaskManagerService o-- ActivityThread
ActivityTaskManagerService o-- ClientLifecycleManager
ActivityTaskManagerService o-- ActivityTaskManagerInternal
ActivityTaskManagerService o-- WindowOrganizerController
ActivityTaskManagerInternal <|-- LocalService
ActivityThread o-- ContextImpl
WindowOrganizerController o-- ActivityTaskManagerService
WindowOrganizerController o-- TaskOrganizerController
ActivityTaskManagerService o-- TaskOrganizerController
WindowOrganizerController o-- DisplayAreaOrganizerController
TaskOrganizerController o-- ActivityTaskManagerService
Context <|-- ContextImpl
ActivityTaskManagerService o-- WindowManagerGlobalLock
WindowOrganizerController o-- WindowManagerGlobalLock
Stub <|-- WindowOrganizerController
IWindowOrganizerController *-- Stub
class ActivityTaskManagerService {
#Context:mContext
#ActivityThread:mSystemThread
#Context:mUiContext
-ClientLifecycleManager:mLifecycleManager
#ActivityTaskManagerInternal:mInternal
#WindowOrganizerController:mWindowOrganizerController
#TaskOrganizerController:mTaskOrganizerController
#WindowManagerGlobalLock:mGlobalLock
}
class ActivityThread {
-ContextImpl:mSystemUiContext
}
class WindowOrganizerController {
-ActivityTaskManagerService:mService
#TaskOrganizerController:mTaskOrganizerController
#DisplayAreaOrganizerController:mDisplayAreaOrganizerController
-WindowManagerGlobalLock:mGlobalLock
}
class TaskOrganizerController {
-ActivityTaskManagerService:mService
}
ActivityTaskManagerService service launch
Then call ActivityTaskManagerService. Lifecycle onStart function
public void onStart(a) {
/ / will be registered in ServiceManager ActivityTaskManagerService object
publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
/ / call ActivityTaskManagerService start function
mService.start();
}
private void start(a) {
/ / analysis shows that this way will ActivityTaskManagerInternal. Class, object and ActivityTaskManagerInternal mInternal of key-value pairs, Registered to LocalServices. SLocalServiceObjects
LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
}
Copy the code
conclusion
In the initialization process of ActivityTaskManagerService, mainly is to initialize the parameters, and then registered in ServiceManager ActivityTaskManagerService object, And will ActivityTaskManagerInternal. Class and object ActivityTaskManagerInternal mInternal key-value pairs, registered to LocalServices. SLocalServiceObjects
The ActivityManagerService object is initialized
mActivityManagerService = ActivityManagerService.Lifecycle.startService(
mSystemServiceManager, atm);
public static ActivityManagerService startService( SystemServiceManager ssm, ActivityTaskManagerService atm) {
sAtm = atm;
return ssm.startService(ActivityManagerService.Lifecycle.class).getService();
}
Copy the code
Similarly, the SystemServiceManager startService function is called here, as you can see from the above analysis
ActivityManagerService. The Lifecycle of the single (Context) constructor calls refs
public Lifecycle(Context context) {
super(context);
mService = new ActivityManagerService(context, sAtm);
}
public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
// Initialize the Injector object
mInjector = new Injector(systemContext);
mContext = systemContext;
mFactoryTest = FactoryTest.getMode();
/ / get SystemServer createSystemContext ActivityThread function to initialize
mSystemThread = ActivityThread.currentActivityThread();
/ / get ActivityThread mSystemUiContext parameter object,
mUiContext = mSystemThread.getSystemUiContext();
/ /... Logs are printed and omitted
// Initialize the ServiceThread object, which inherits from HandlerThread
mHandlerThread = new ServiceThread(TAG,
THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
mHandlerThread.start();
// Mainhandler is an inner class of ActivityManagerService
// mHandlerThread is associated with the mHandlerThread Looper described above
mHandler = new MainHandler(mHandlerThread.getLooper());
// Initializes a UiHandler object that inherits from Handler
mUiHandler = mInjector.getUiHandler(this);
// Initialize a ServiceThread with the parameter mProcStartHandlerThread
// Create a new Handler associated with it
mProcStartHandlerThread = new ServiceThread(TAG + ":procStart",
THREAD_PRIORITY_FOREGROUND, false /* allowIo */);
mProcStartHandlerThread.start();
mProcStartHandler = new Handler(mProcStartHandlerThread.getLooper());
// Mainly registers and collects constants that change the state of ActivityManager
mConstants = new ActivityManagerConstants(mContext, this, mHandler);
// Store and manipulate valid UIDS of running processes
final ActiveUids activeUids = new ActiveUids(this.true /* postChangesToAtm */);
// SystemService collects and reports compatibility changes
mPlatformCompat = (PlatformCompat) ServiceManager.getService(
Context.PLATFORM_COMPAT_SERVICE);
// Get the ProcessList object and initialize it
// This class is mainly used to deal with ActivityManager processes
mProcessList = mInjector.getProcessList(this);
mProcessList.init(this, activeUids, mPlatformCompat);
// LowMemDetector object initialization, low memory monitoring
// Use PSI to monitor low memory. If the kernel does not support PSI, this class is unavailable
// PSI is a new feature introduced in Android Q, we can study it later
mLowMemDetector = new LowMemDetector(this);
// OOM for monitoring processes
mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids);
/ / monitor BROADCAST_GF_CONSTANTS
// Broadcast policy parameters
final BroadcastConstants foreConstants = new BroadcastConstants(
Settings.Global.BROADCAST_FG_CONSTANTS);
foreConstants.TIMEOUT = BROADCAST_FG_TIMEOUT;
final BroadcastConstants backConstants = new BroadcastConstants(
Settings.Global.BROADCAST_BG_CONSTANTS);
backConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
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);
// Initialize the broadcast queue
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;
// Initialize the ActiveServices object
// Manage effective services in the background
mServices = new ActiveServices(this);
// Initialize the ProviderMap object
// This object categorizes contentProviders so that they can be easily traced by authorized processes or classes
// It can distinguish between contentProviders that are tracked by users and those that are not tracked by specific users
mProviderMap = new ProviderMap(this);
// Initialize the PackageWatchdog object
// The main purpose of this object is to monitor the health of applications in the system and notify associated observers when errors or exceptions occur
// In the event of an application error, the registered observer will handle or mitigate the error or exception in a way that has the least impact on the user side
mPackageWatchdog = PackageWatchdog.getInstance(mUiContext);
// Handle application error messages
mAppErrors = new AppErrors(mUiContext, this, mPackageWatchdog);
// Initializes and confirms that the /data/system/ directory is created and returns File information for this directory
final File systemDir = SystemServiceManager.ensureSystemDir();
// TODO: Move creation of battery stats service outside of activity manager service.
// Initialize the BatteryStatsService object
// This object collects all the events that affect the life of the phone
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);
// Service to collect process information
mProcessStats = new ProcessStatsService(this.new File(systemDir, "procstats"));
// Initialize the AppOpsService object
mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);
// Get the UriGrantsManagerInternal object
mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
// Initializes the UserController object to manage multi-user processes for ActivityManagerService
mUserController = new UserController(this);
// Initialize the PendingIntentController object to manage the PendingIntent for ActivityManagerService
mPendingIntentController = new PendingIntentController(
mHandlerThread.getLooper(), mUserController, mConstants);
/ /... Function independent code, omitted
mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
/ / initialization ActivityTaskManagerService object configuration
mActivityTaskManager = atm;
mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController,
DisplayThread.get().getLooper());
/ / get LocalService objects, the class inherits from ActivityTaskManagerInternal
/ / loading position in ActivityTaskManagerService
mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);
// Initializes a thread to track CPU running status
mProcessCpuThread = new Thread("CpuTracker") {
@Override
public void run(a) {
/ /... No analysis here, the code is temporarily omitted}}; mHiddenApiBlacklist =new HiddenApiSettings(mHandler, mContext);
// Initialize Watchdog and add ActivityManagerService listener
// here Watchdog adds a listener to see if a deadlock occurs in AMS
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.mCachedAppOptimizer.mCachedAppOptimizerThread.getThreadId(),
Process.THREAD_GROUP_SYSTEM);
} catch (Exception e) {
Slog.w(TAG, "Setting background thread cpuset failed");
}
mInternal = new LocalService();
mPendingStartActivityUids = new PendingStartActivityUids(mContext);
}
Copy the code
For this constructor, which initializes some corresponding objects and initializes some corresponding objects, only a class diagram of ActivityManagerService is generated
classDiagram Stub <|-- ActivityManagerService IActivityManager *-- Stub Watchdog *-- Monitor <<interface>> Monitor Monitor <|.. ActivityManagerService BatteryStatsImpl *-- BatteryCallback <<interface>> BatteryCallback BatteryCallback <|.. ActivityManagerService ActivityManagerService --> Injector : mInjector ActivityManagerService --> Context : mContext ActivityManagerService --> ActivityThread : mSystemThread ActivityManagerService --> ServiceThread ActivityManagerService --> MainHandler : mHandler ActivityManagerService --> UiHandler : mUiHandler ActivityManagerService --> Handler : mProcStartHandler ActivityManagerService --> ActivityManagerConstants : mConstants ActivityManagerService --> ProcessList : mProcessList ActivityManagerService --> LowMemDetector : mLowMemDetector ActivityManagerService --> OomAdjuster : mOomAdjuster ActivityManagerService --> ActiveServices:mServices ActivityManagerService --> ProviderMap:mProviderMap ActivityManagerService --> PackageWatchdog:mPackageWatchdog ActivityManagerService --> AppErrors:mAppErrors ActivityManagerService --> BatteryStatsService:mBatteryStatsService ActivityManagerService --> OomAdjProfiler:mOomAdjProfiler ActivityManagerService --> ProcessStatsService:mProcessStats ActivityManagerService --> AppOpsService:mAppOpsService ActivityManagerService --> UriGrantsManagerInternal:mUgmInternal ActivityManagerService --> UserController:mUserController ActivityManagerService --> PendingIntentController:mPendingIntentController ActivityManagerService --> ActivityTaskManagerService:mActivityTaskManager ActivityManagerService --> IntentFirewall:mIntentFirewall ActivityManagerService --> ActivityTaskManagerInternal:mAtmInternal ActivityManagerService --> HiddenApiSettings:mHiddenApiBlacklist ActivityManagerService --> PendingStartActivityUids:mPendingStartActivityUids ActivityManagerService --> LocalService:mInternal ActivityManagerInternal <|-- LocalService class ActivityManagerService { #mProcStartHandlerThread:ServiceThread #mHandlerThread:mHandlerThread #mFgBroadcastQueue:BroadcastQueue #mBgBroadcastQueue:BroadcastQueue #mOffloadBroadcastQueue:BroadcastQueue #mBroadcastQueues:BroadcastQueue[] +mProcessCpuThread:Thread } class ActivityThread { +currentActivityThread() +getSystemUiContext() } class Injector { +getUiHandler(ActivityManagerService) +getProcessList(ActivityManagerService) +getAppOpsService(File, MainHandler) } class ProcessList { +init(ActivityManagerService, ActiveUids, PlatformCompat) } class BatteryStatsService { +getActiveStatistics() +scheduleWriteToDisk() } class OomAdjProfiler { +batteryPowerChanged(boolean) } class ActivityTaskManagerService { +initialize(IntentFirewall, PendingIntentController, Looper) }
Also, a sequence diagram of the AMS constructor
The sequence diagram here is only for process recording, not for expansion analysis
ActivityManagerService. The Lifecycle of the onStart function calls
public void onStart(a) {
mService.start();
}
private void start(a) {
removeAllProcessGroups();
// While an infinite loop updates the current CPU status
mProcessCpuThread.start();
/ / will BatteryStatsService. Registered to LocalServices LocalService. SLocalServiceObjects, LocalService inherited from BatteryStatsInternal class
// Register the BatteryStatsService object with the service manager
mBatteryStatsService.publish();
/ / will AppOpsService. AppOpsManagerInternalImpl registered to LocalServices. SLocalServiceObjects
// Register the AppOpsService object with the service manager
mAppOpsService.publish();
Slog.d("AppOps"."AppOpsService published");
/ / ActivityManagerInternal object mInternal registered to LocalServices. SLocalServiceObjects
LocalServices.addService(ActivityManagerInternal.class, mInternal);
/ / after completion of the above registered LocalServices, access to the object in the ActivityTaskManagerService
mActivityTaskManager.onActivityManagerInternalAdded();
After registering LocalServices as described above, obtain the object in PendingIntentController
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.
// The lock is waiting for the mProcessCpuTracker to finish loading
try {
mProcessCpuInitLatch.await();
} catch (InterruptedException e) {
Slog.wtf(TAG, "Interrupted wait during start", e);
Thread.currentThread().interrupt();
throw new IllegalStateException("Interrupted wait during start"); }}Copy the code
As you can see, the AMS start function registers services primarily to ServiceManager and LocalServices
conclusion
When Lifecycle, a subclass of AMS, is started through SystemServiceManager,
- First call the constructor of AMS initialized to AMS, in the constructor initializes the AMS some necessary parameters and class object, during the period of constructor calls, will be called at the same time do some initialization ActivityTaskManagerService the initialize function
- The next step is to call AMS’s start function to start monitoring the CPU, and then register the necessary services with LocalServices and ServiceManager
Main is: Will BatteryStatsInternal. Class and BatteryStatsService. LocalService of keys to register to LocalServices. SLocalServiceObjects Register the “BatteryStats” and BatteryStatsService objects as key-value pairs with the ServiceManager. Register the “Appops” and AppOpsService objects as key-value pairs with the ServiceManager Will AppOpsManagerInternal. Class and AppOpsService. MAppOpsManagerInternal of keys to register to LocalServices. SLocalServiceObjects