The Android PackageManagerService10.0 interpretation of source code (AndroidManifest. XML parsing)

Android determines whether an Activity is registered in androidmanifest.xml.

# Android ActivityManagerService(AMS) source code analysis

Android ActivityManagerService(AMS) source analysis

Too much content, suggested collection

Introduction of AMS

ActivityManagerService is a very important system service in Android system, and it is also one of the system services that we deal with most in upper-layer apps. ActivityManagerService (AMS) is responsible for the startup, switchover, and scheduling of the four components, as well as the management and scheduling of application processes. All apps need AMS. Activity Manager consists of the following parts:

  1. Service proxy: Implemented by ActivityManagerProxy, it is used for interprocess communication with system services provided by the Server
  2. Service hub: ActivityManagerNative inherits from Binder and implements IActivityManager, which provides service interfaces and

Binder interface to each other, and internally store the service proxy image, and provides getDefault method to return the service proxy 3.. Client: The ActivityManager encapsulates part of the service interface for the Client to call. Inside ActivityManager, you get a reference to the ActivityManagerProxy object by calling ActivityManagerNative’s getDefault method, 4. Server: Implemented by ActivityManagerService, provides system services on the Server side

Start process of ActivityManagerService

AMS is added in SystemServer, so check initialization in SystemServer first.

public static void main(String[] args) {
        new SystemServer().run();
    }
Copy the code
private void run(a){...// Initialize the system 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(); . }Copy the code

In SystemServer, start AMS in startBootstrapServices()

 private void startBootstrapServices(a) {...// Activity manager runs the show.
        traceBeginAndSlog("StartActivityManager");
        // Start AMSmActivityManagerService = 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();
    }
Copy the code

AMS is through SystemServiceManager startService to start, parameter is ActivityManagerService. Lifecycle. The class, take a look first at startService method.

@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);
    }
Copy the code
	@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 {
                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); }}Copy the code
 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");
    }
Copy the code

The startService method is simple. It takes the incoming class and reflects it to create the corresponding Service. So an instance of Lifecycle is created and the AMS service is started with startService. Could look at the ActivityManagerService. Lifecycle the constructor of a class.

public static final class Lifecycle extends SystemService {
        private final ActivityManagerService mService;

        public Lifecycle(Context context) {
            super(context);
            mService = new ActivityManagerService(context);
        }

        @Override
        public void onStart(a) {
            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(a) {
            returnmService; }}Copy the code
AMS initialization does a lot of things. For details, see ActivityManagerService,

Concrete has a

  • mSystemThread = ActivityThread.currentActivityThread(); // Get the current ActivityThread
  • mUiContext = mSystemThread.getSystemUiContext(); / / assignment mUiContext
  • Create a Handler thread to process Handler messages
  • mUiHandler = mInjector.getUiHandler(this); // Handler to handle UI-related MSG
  • MConstants = new ActivityManagerConstants(this, mHandler)
  • Initialize the queue that manages foreground and background broadcasts, MFgBroadcastQueue = new BroadcastQueue(this, mHandler, “foreground”, BROADCAST_FG_TIMEOUT, false);
  • MServices = new ActiveServices(this);
  • mProviderMap = new ProviderMap(this); // Initialize the Provider manager
  • mAppErrors = new AppErrors(mUiContext, this); // Initializes the printer for APP error logs
  • Statistical service, create the battery and output to the specified directory File dataDir = Environment. GetDataDirectory ();
  • Create process statistical analysis service, track statistics which processes have abused or bad behavior: mBatteryStatsService. GetActiveStatistics () getIsOnBattery ();
  • MGrantFile = new AtomicFile(new File(systemDir, “urigrants. XML “), “URi-grants “);
  • MUserController = new UserController(this);
  • MVrController = new VrController(this);
  • Example Initialize the OpenGL version number
  • The important class that manages ActivityStack, which records activity state information, is the core AMS class mStackSupervisor = createStackSupervisor();
  • // Controls Keyguard occlusion, closure, and conversion depending on the type of Activity currently visible. Keyguard is our lock screen related page mKeyguardController = mStackSupervisor. GetKeyguardController ();
  • Manage the APK compatibility configuration parsing /data/system/ package-compat.xml file, which is used to store APK information that requires consideration of screen size, mCompatModePackages = new CompatModePackages(this, systemDir, mHandler);
  • Intent firewall. Google defines a set of rules to filter intents. If they fire, the Intent will be discarded by the system. MIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
  • This is the class that handles the intent and flag used to start an activity. MActivityStartController = new ActivityStartController(this);
  • Start a thread to track the current STATE of the CPU. AMS knows the current STATE of the CPU so that other tasks can be arranged more efficiently
  • A watchdog, listening for progress. This class calls the monitor every minute. Kill watchdog.getInstance ().addmonitor (this) if the process does not return anything
  • Wait for mProcessCpuThread completion of initialization, releases the lock, access denied mProcessCpuInitLatch during initialization. Await ()
SetSystemProcess () does something
  1. Register services: First register ActivityManagerService with the ServiceManager, then register several services related to system performance debugging with the ServiceManager
  2. Query and process ApplicationInfo. The interface of the PackageManagerService is called to query the ApplicationInfo information of the application whose package name is Android, corresponding to Framework-res.apk. And then to the information for the parameter called ActivityThread installSystemApplicationInfo method.
  3. Create and process ProcessRecord. Call newProcessRecordLocked on ActivityManagerService to create an object of type ProcessRecord and save the information for that object

What is AMS?

  1. From a Java perspective, AMS is a Java object that implements the Ibinder interface, so it is used for communication between processes

This object is initialized in the run() method of SystemServer.java. ActivityManagerService, as its name suggests, is a service that manages activities, and a system service that manages package management, battery management, vibration management, etc. AMS implements the Ibinder interface, so it is a Binder, which means it can be used for interprocess communication as well as as a thread, because a Binder is a thread.

If we start a Hello World Android application, and we don’t start any other threads in it, we need to start at least four threads in this application.

  1. The main thread, just the main thread of the program, is also the most commonly used thread, also called the UI thread, because of android components

It is not thread-safe, so only the UI/MAIN thread is allowed to operate. Binder1 is our ApplicationThread. This class implements the Ibinder interface and is used for communication between processes. Binder2 is our ViewRoot.W object, which also implements the IBinder interface, which is the tool used for our application to communicate with WMS.

WMS is the Windows ManagerServicer, similar to AMS but a system service that manages Windows.

public class ActivityManagerService extends IActivityManager.Stub implements Watchdog.Monitor.BatteryStatsImpl.BatteryCallback {}
Copy the code

AMS related important class introduction

ProcessRecord data structure
The first type of data: data that describes identity
  • ApplicationInfo Info: Application information defined in androidmanifest.xml
  • Boolean Isolated: Indicates whether the process is isolated
  • Int uid: indicates the process UID
  • Int userId: This is a multi-user system ID for Android, just like Windows can log in to many users, Android

It is hoped that similar multi-users can be implemented

  • String processName: processName, package name by default
  • IApplicationThread thread: This is important. It is the client of ApplicationThread, through which AMS passes

Object that sends asynchronous messages to the APK process, so the apK process is used only if the object is not empty

  • Int PID: indicates the PID of a process
The second type of data: data that describes components in a process
  • PkgList: package to run in a process
  • ArraySet pkgDeps: package on which the process runs
  • ArrayList Activities: A list of all activity components that a process has started
  • ArraySet Services: A record of all service components started by a process
  • ArraySet Receivers: A recording list of broadcast receivers
  • ArrayList conProviders: client record table using ContentProvider
  • 10.BroadcastRecord curReceiver: BroadcastRecord curReceiver that the current process is executing
Third type of data: data that describes process status
  • Int maxAdj: ad_upper limit of a process (adjustment)
  • Int curRawAdj: the current adj. this value may be greater than maxAdj
  • Int setRawAdj: adj after the curRawAdj set to the Lowmemorykiller system was last evaluated
  • Int curAdj: the current adj. this is the value of curRawAdj truncated by maxAdj
  • Int pssProcState: indicates the PSS process status
The fourth type of data: data related to PSS

Vss-virtual Set Size Virtual memory (including memory occupied by the shared library) RSs-resident Set Size Proportional Size of actual physical memory (including memory occupied by the shared library) Uss-unique Set Size Physical memory used by a process (excluding memory used by a shared library) The Size of memory used by a process is as follows: VSS >= RSS >= PSS >= USS

  • . Long initialIdlePss: initializes the PSS
  • .long lastPss: lastPss
  • .long lastSwapPss: lastSwapPss data
  • Long lastCachedPss: lastCachedPss data
  • Long lastCachedSwapPss: indicates the lastCachedSwapPss data
Fifth type of data: time related data
  • Long lastActivityTime: the last time it was used
  • Long lastStateTime: time when the process state was last set
  • Long fgInteractionTime: Time to become foreground
The sixth type of data: data related to crash and ANR
  • DeathRecipient: This object is triggered when the APK process exits

The binderDied() method to reclaim system resources

  • Boolean crashing: A process has crashed
  • Dialog crashDialog: Indicates the crashDialog box
  • Dialog anrDialog: ANR displays the Dialog box
  • String waitingToKill: Reason why a background process is killed
Seventh type of data: data related to instrumentation

Instrumentation can also be said to be a component of APK, if we provide it, the system will default to the use of instrumentation. Java class, according to our general understanding, UI thread control activity life cycle, is a direct call to the activity class method, The time is like this. The UI thread calls the instrumentation method, which calls the Activity lifecycle methods, so if we overwrite the instrumentation methods, we can understand the lifecycle of all activities.

  • ComponentName instrumentationClass: Instrumentation messages defined in Androidmanifest.xml
  • ApplicationInfo instrumentationInfo: Instrumentation application information
  • String instrumentationProfileFile: instrumentation configuration file
  • IInstrumentationWatcher instrumentationWatcher: Instrumentation monitor
Class 8 data: power information and debugging information
  • BatteryStatsImpl mBatteryStats: Indicates the battery quantity
  • BatteryStatsImpl. Uid. Proc curProcBatteryStats: the current process power information
  • Boolean debugging: The Boolean is being debugged
  • Boolean waitedForDebugger: Waits for debugging
  • Dialog waitDialog: waitDialog box
ProcessRecord container
Internal container for recording table of four components

Component running is the meaning of the process, due to the seamless integration between the Android system processes, so the system needs to control the component level, all the component information needs to be mapped to the system, an ActivityRecord corresponds to an Activity information, A ServiceRecord record corresponds to a Service, a ConnectionRecord corresponds to a bind Service client, and a ReceiverList corresponds to a group of broadcasts that process the same event. A ContentProviderRecord corresponds to a ContentProvider message, A ContentProviderConnection corresponds to a process of all the ContentProvider client. The activity records: activities: The container for ActivityRecord, a service record of all activity components started by a process

  • Services: a container for ServiceRecord, a record of all service components started by a process
  • ExecutingServices: How do you define a ServiceRecord that is running? The first thing that needs to be clarified is how does the system control the components? A message is sent to the APK process and an APK process processes the message and reports that the message is completed. Executing a message is defined as the time that a message is sent until the report is completed
  • Connections: A client record table bound to a Service

Receivers: Receiver: ReceiverList receiver

  • PubProviders: a mapping of names to ContentProviderRecord, pub stands for publish,

The ContentProvider needs to be installed and published to the system (AMS) before it can be used. Installation means that the APK process loads the ContentProvider subclass, initializes it, creates a database, and so on. Publishing is to register the Binder client side of the ContentProvider with AMS

  • ContProviders: ContentProviderConnection container, using a ContentProvider client record
Data structures related to Activity management
ActivityRecord

ActivityRecord, An entry in the history stack, representing An activity. An entry in the history stack that represents an activity. There are a number of member variables in an ActivityRecord that contain all the information about an Activity. The member variable task in ActivityRecord represents the TaskRecord in which it is located. ActivityRecord establishes a link with TaskRecord, \frameworks\ Base \services\core\ Java \com\ Android \server\am\ActivityStarter. Java

TaskRecord

TaskRecord, Internal maintenance of an ArrayList to store ActivityRecord \frameworks\ Base \services\core\ Java \com\ Android \server\am\ taskRecord.java You can see that TaskRecord uses an ArrayList to hold all activityRecords. Similarly, mStack in TaskRecord represents the ActivityStack on which it is located. StartActivity () also creates a TaskRecord.

ActivityStarter

frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java

ActivityStack

ActivityStack uses an ArrayList to store TaskRecords. ActivityStack uses an ArrayList to store taskRecords. In addition, ActivityStack also holds an ActivityStackSupervisor object, which is used to manage ActivityStacks. The ActivityStack is created by the ActivityStackSupervisor, which actually manages the ActivityStack.

ActivityStackSupervisor

ActivityStackSupervisor, as the name suggests, Is used to manage ActivityStack frameworks/base/services/core/Java/com/android/server/am/ActivityStackSupervisor. Java There are two different ActivityStack objects inside ActivityStack, mHomeStack and mFocusedStack, that manage different tasks. ActivityStackSupervisor contains methods to create ActivityStack objects. An ActivityStackSupervisor object is created when AMS is initialized.

Last few pictures