Android AMS 原理理解

230 阅读42分钟

ActivityManagerService服务是Android系统核心服务,负责Android管理系统Activity,Service,ContentProvider和BroadcastReceiver 四大组件,同时还负责Android系统中的进程管理。由此可见ActivityManagerService服务对于Android系统来讲非常重要,我们就从以下几个方面来了解下AMS服务。

  • AMS服务的启动和初始化过程
  • AMS如何启动和管理Activity
  • AMS如何启动和管理Service
  • AMS如何管理BroadCastReceiver
  • AMS如何管理ContentProvider 此篇文章就来总结下Ams服务的启动和初始化过程

系统进程运行环境的初始化

在分析AMS服务之前需要先来了解下什么是Context.

一、Context是什么?

Context是一个抽象类,其通用实现在ContextImpl类中。是一个访问application环境全局信息的接口,通过它可以访问application的资源和相关的类,其主要功能如下:

• 启动Activity • 启动和停止Service • 发送广播消息(Intent) • 注册广播消息(Intent)接收者 • 可以访问APK中各种资源(如Resources和AssetManager等) • 可以访问Package的相关信息 • APK的各种权限管理

context实现

image.png

Context的类关系图可知,ContextImpl最终实现了Context相关方法,ContextWrapper只是一个代理类,Activity,Service,Application都是实现了ContextWrapper,所以在Activity,Service和Application中调用的context的相关方法,最终都有ContextImpl来实现。

image.png

Android系统中的进程分为两种,应用进程和系统进程。而ActivityThread就是应用进程的主线程,Android系统的应用进程启动后首先运行ActivityThread的main函数,ActivityThread和AMS进行通信,调度和执行应用进程的四大组件。  SystemServer是Android的系统进程,由于系统进程中也有一些Activity和系统资源,为了保证调用方式统一,系统进程也需要ActivityThread和Context等Android运行环境。所以SystemServer也是一个特殊的应用进行,对Android而言系统进程而言,SysrtemServer也是一个特别的应用程序,也有自己的Context上下文环境,而系统的Context又是怎么创建的呢?\color{#FF3030}{怎么创建的呢?}

系统的Context是SystemServer启动之后,在createSystemContext方法中创建的。

private void createSystemContext() {
      ActivityThread activityThread = ActivityThread.systemMain();
       mSystemContext = activityThread.getSystemContext(); ////【SystemServer】的此处创建
       mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);

       final Context systemUiContext = activityThread.getSystemUiContext();
       systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
   }

第一步ActivityThread.systemMain方法,该方法生成了一个ActivityThread对象。

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 thread = new ActivityThread();//  【ActivityThread】 的此处创建
        thread.attach(true);
        return thread;
    }

首先创建了一个ActivityThread对象,然后调用attach方法。 ActivityThread的构造方法很简单就是创建了一个ResourcesManager对象,用于管理应用程序中的资源文件

2118    ActivityThread() {
2119        mResourcesManager = ResourcesManager.getInstance();
2120    }

那就接着看ActivityThread的Attach方法。

private void attach(boolean system) {
6316        sCurrentActivityThread = this;
6317        mSystemThread = system;
6318        if (!system) {
6319            ViewRootImpl.addFirstDrawHandler(new Runnable() {
6320                @Override
6321                public void run() {
6322                    ensureJitEnabled();
6323                }
6324            });
6325            android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
6326                                                    UserHandle.myUserId());
6327            RuntimeInit.setApplicationObject(mAppThread.asBinder());
6328            final IActivityManager mgr = ActivityManager.getService();
6329            try {
6330                mgr.attachApplication(mAppThread);
6331            } catch (RemoteException ex) {
6332                throw ex.rethrowFromSystemServer();
6333            }
6334            // Watch for getting close to heap limit.
6335            BinderInternal.addGcWatcher(new Runnable() {
6336                @Override public void run() {
6337                    if (!mSomeActivitiesChanged) {
6338                        return;
6339                    }
6340                    Runtime runtime = Runtime.getRuntime();
6341                    long dalvikMax = runtime.maxMemory();
6342                    long dalvikUsed = runtime.totalMemory() - runtime.freeMemory();
6343                    if (dalvikUsed > ((3*dalvikMax)/4)) {
6344                        if (DEBUG_MEMORY_TRIM) Slog.d(TAG, "Dalvik max=" + (dalvikMax/1024)
6345                                + " total=" + (runtime.totalMemory()/1024)
6346                                + " used=" + (dalvikUsed/1024));
6347                        mSomeActivitiesChanged = false;
6348                        try {
6349                            mgr.releaseSomeActivities(mAppThread);
6350                        } catch (RemoteException e) {
6351                            throw e.rethrowFromSystemServer();
6352                        }
6353                    }
6354                }
6355            });
6356        } else {
6357            // Don't set application object here -- if the system crashes,
6358            // we can't display an alert, we just want to die die die.
6359            android.ddm.DdmHandleAppName.setAppName("system_process",
6360                    UserHandle.myUserId());   //  【修改系统进程的名称】为system_process
6361            try {
6362                mInstrumentation = new Instrumentation();//【工具类】AMS的指令创建和调度交互都由它来执行
6363                ContextImpl context = ContextImpl.createAppContext(// 【创建】一个该进程相关的【context】对象
6364                        this, getSystemContext().mPackageInfo);
6365                mInitialApplication = context.mPackageInfo.makeApplication(true, null);
6366                mInitialApplication.onCreate();
6367            } catch (Exception e) {
6368                throw new RuntimeException(
6369                        "Unable to instantiate Application():" + e.toString(), e);
6370            }
6371        }
6372
6373        // add dropbox logging to libcore
6374        DropBox.setReporter(new DropBoxReporter());
6375
6376        ViewRootImpl.ConfigChangedCallback configChangedCallback
6377                = (Configuration globalConfig) -> {
6378            synchronized (mResourcesManager) {
6379                // We need to apply this change to the resources immediately, because upon returning
6380                // the view hierarchy will be informed about it.
6381                if (mResourcesManager.applyConfigurationToResourcesLocked(globalConfig,
6382                        null /* compat */)) {
6383                    updateLocaleListFromAppContext(mInitialApplication.getApplicationContext(),
6384                            mResourcesManager.getConfiguration().getLocales());
6385
6386                    // This actually changed the resources! Tell everyone about it.
6387                    if (mPendingConfiguration == null
6388                            || mPendingConfiguration.isOtherSeqNewer(globalConfig)) {
6389                        mPendingConfiguration = globalConfig;
6390                        sendMessage(H.CONFIGURATION_CHANGED, globalConfig);
6391                    }
6392                }
6393            }
6394        };
6395        ViewRootImpl.addConfigCallback(configChangedCallback);
6396    }

attach方法传进来的参数为true,代表该进程为系统进程,所以直接看else中的方法实现。  首先调用setAppName将系统应用的名称改为system_process,调试的时候我们可以看到系统的进程名称为system_process.  然后创建了一个Instrumentation类,该类是一个工具类,ActivityThread接收到AMS的指令创建和调度交互都由它来执行。  然后调用createAppContext来创建一个系统的ContextImpl的大管家,传入的关键参数为系统进程的apk相关信息。后面再分析getSystemContext方法,然后创建了一个android,app.application,并调用了它的onCreate方法。

getSystemContext方法

 public ContextImpl getSystemContext() {
2154        synchronized (this) {
2155            if (mSystemContext == null) {
2156                mSystemContext = ContextImpl.createSystemContext(this);
2157            }
2158            return mSystemContext;
2159        }
2160    }

systemContext最终由ContextImpl.createSystemContext方法来创建。

static ContextImpl createSystemContext(ActivityThread mainThread) {
2244        LoadedApk packageInfo = new LoadedApk(mainThread);
2245        ContextImpl context = new ContextImpl(null, mainThread, packageInfo, null, null, null, 0,
2246                null);
2247        context.setResources(packageInfo.getResources());
2248        context.mResources.updateConfiguration(context.mResourcesManager.getConfiguration(),
2249                context.mResourcesManager.getDisplayMetrics());
2250        return context;
2251    }

首先创建了一个LoadedApk对象,然后根据LoadedApk对象创建了一个ContextImpl对象。 LoadedApk代表一个加载到系统中的APK。 其中保存了apk的基本信息

/**
181     * Create information about the system package.
182     * Must call {@link #installSystemApplicationInfo} later.
183     */
184    LoadedApk(ActivityThread activityThread) {
185        mActivityThread = activityThread;
186        mApplicationInfo = new ApplicationInfo();【 【该applicationInfo并没有指向任何一个应用 】】
187        mApplicationInfo.packageName = "android";
188        mPackageName = "android";
189        mAppDir = null;
190        mResDir = null;
191        mSplitAppDirs = null;
192        mSplitResDirs = null;
193        mSplitClassLoaderNames = null;
194        mOverlayDirs = null;
195        mDataDir = null;
196        mDataDirFile = null;
197        mDeviceProtectedDataDirFile = null;
198        mCredentialProtectedDataDirFile = null;
199        mLibDir = null;
200        mBaseClassLoader = null;
201        mSecurityViolation = false;
202        mIncludeCode = true;
203        mRegisterPackage = false;
204        mClassLoader = ClassLoader.getSystemClassLoader();
205        mResources = Resources.getSystem();
206    }

LoadedAPK的这个构造方法只有系统进程创建的时候可以调用。它代表一个系统进程的apk,它里面存储着资源文件的位置,jni包的位置等信息,包名为android。其实代表的就是就是framework-res.apk。该apk仅供systemServer使用。

ContextImpl的构造方法

private ContextImpl(@Nullable ContextImpl container, @NonNull ActivityThread mainThread,
2324            @NonNull LoadedApk packageInfo, @Nullable String splitName,
2325            @Nullable IBinder activityToken, @Nullable UserHandle user, int flags,
2326            @Nullable ClassLoader classLoader) {
2327        mOuterContext = this;
2328
2329        // If creator didn't specify which storage to use, use the default
2330        // location for application.
2331        if ((flags & (Context.CONTEXT_CREDENTIAL_PROTECTED_STORAGE
2332                | Context.CONTEXT_DEVICE_PROTECTED_STORAGE)) == 0) {
2333            final File dataDir = packageInfo.getDataDirFile();
2334            if (Objects.equals(dataDir, packageInfo.getCredentialProtectedDataDirFile())) {
2335                flags |= Context.CONTEXT_CREDENTIAL_PROTECTED_STORAGE;
2336            } else if (Objects.equals(dataDir, packageInfo.getDeviceProtectedDataDirFile())) {
2337                flags |= Context.CONTEXT_DEVICE_PROTECTED_STORAGE;
2338            }
2339        }
2340//framework-res.apk的【主进程】为当前的【ActivityThread】
2341        mMainThread = mainThread;
2342        mActivityToken = activityToken;
2343        mFlags = flags;
2344
2345        if (user == null) {
2346            user = Process.myUserHandle();
2347        }
2348        mUser = user;
2349           //  【packageinfo的信息】
2350        mPackageInfo = packageInfo;
2351        mSplitName = splitName;
2352        mClassLoader = classLoader;
2353        mResourcesManager = ResourcesManager.getInstance(); //【初始化资源管理器】
2354
2355        if (container != null) {
2356            mBasePackageName = container.mBasePackageName;
2357            mOpPackageName = container.mOpPackageName;
2358            setResources(container.mResources);
2359            mDisplay = container.mDisplay;
2360        } else {
2361            mBasePackageName = packageInfo.mPackageName;
2362            ApplicationInfo ainfo = packageInfo.getApplicationInfo();
2363            if (ainfo.uid == Process.SYSTEM_UID && ainfo.uid != Process.myUid()) {
2364                // Special case: system components allow themselves to be loaded in to other
2365                // processes.  For purposes of app ops, we must then consider the context as
2366                // belonging to the package of this process, not the system itself, otherwise
2367                // the package+uid verifications in app ops will fail.
2368                mOpPackageName = ActivityThread.currentPackageName();
2369            } else {
2370                mOpPackageName = mBasePackageName;
2371            }
2372        }
2373    // 【初始化系统的contentResolver】
2374        mContentResolver = new ApplicationContentResolver(this, mainThread, user);
2375    }

 调用ContextImpl的构造方法生成了一个ContextImpl。该构造方法主要就是初始化了ContextImpl中的一些信息,如ResourManager等。同时将刚才创建的LoadAPK的package信息保存到的Context中,最终生成了一个和系统进程相关的Context。因为它保存了系统相关的信息

 调用systemMain函数结束后,首先生成了一个ActivityThread对象,它代表应用进程的主线程。得到一个Context对象,它背后所指向的Application环境与framework-res.apk有关。  这两样东西就构成了Android程序的运行环境。我们自己写的apk的代码最终在ActivityThread线程上运行,通过Context应用程序的大管家,可以调用进程所用到的资源和方法。  为什么要为系统进程设置应用的运行环境呢,因为系统进程中包含了一个framewrok-res.apk的应用进程,这个apk也需要一个运行环境。  在SystemServer进程中也创建了一个Android运行环境,说明SystemServer系统进程也被看做一个特殊的应用程序。因为系统进程中也会有Activity界面和资源,所以也为他创建了一个运行环境,这样做它就可以和普通应用进程一样使用统一的接口和系统交互了。

启动AMS服务过程。

AMS服务的启动过程和其他系统服务的启动过程一样,也是在SystemServer.run()服务中启动起来的。

/**
264     * The main entry point from zygote.
265     */
266    public static void main(String[] args) {
267        new SystemServer().run();
268    }

private void run() {
278        try {
279            traceBeginAndSlog("InitBeforeStartServices");
280            // If a device's clock is before 1970 (before 0), a lot of
281            // APIs crash dealing with negative numbers, notably
282            // java.io.File#setLastModified, so instead we fake it and
283            // hope that time from cell towers or NTP fixes it shortly.
284            if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
285                Slog.w(TAG, "System clock is before 1970; setting to 1970.");
286                SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
287            }
288
289            //
290            // Default the timezone property to GMT if not set.
291            //
292            String timezoneProperty =  SystemProperties.get("persist.sys.timezone");
293            if (timezoneProperty == null || timezoneProperty.isEmpty()) {
294                Slog.w(TAG, "Timezone not set; setting to GMT.");
295                SystemProperties.set("persist.sys.timezone", "GMT");
296            }
297
298            // If the system has "persist.sys.language" and friends set, replace them with
299            // "persist.sys.locale". Note that the default locale at this point is calculated
300            // using the "-Duser.locale" command line flag. That flag is usually populated by
301            // AndroidRuntime using the same set of system properties, but only the system_server
302            // and system apps are allowed to set them.
303            //
304            // NOTE: Most changes made here will need an equivalent change to
305            // core/jni/AndroidRuntime.cpp
306            if (!SystemProperties.get("persist.sys.language").isEmpty()) {
307                final String languageTag = Locale.getDefault().toLanguageTag();
308
309                SystemProperties.set("persist.sys.locale", languageTag);
310                SystemProperties.set("persist.sys.language", "");
311                SystemProperties.set("persist.sys.country", "");
312                SystemProperties.set("persist.sys.localevar", "");
313            }
314
315            // The system server should never make non-oneway calls
316            Binder.setWarnOnBlocking(true);
317
318            // Here we go!
319            Slog.i(TAG, "Entered the Android system server!");
320            int uptimeMillis = (int) SystemClock.elapsedRealtime();
321            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, uptimeMillis);
322            if (!mRuntimeRestart) {
323                MetricsLogger.histogram(null, "boot_system_server_init", uptimeMillis);
324            }
325
326            // In case the runtime switched since last boot (such as when
327            // the old runtime was removed in an OTA), set the system
328            // property so that it is in sync. We can | xq oqi't do this in
329            // libnativehelper's JniInvocation::Init code where we already
330            // had to fallback to a different runtime because it is
331            // running as root and we need to be the system user to set
332            // the property. http://b/11463182
333            SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
334
335            // Mmmmmm... more memory!
336            VMRuntime.getRuntime().clearGrowthLimit();
337
338            // The system server has to run all of the time, so it needs to be
339            // as efficient as possible with its memory usage.
340            VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
341
342            // Some devices rely on runtime fingerprint generation, so make sure
343            // we've defined it before booting further.
344            Build.ensureFingerprintProperty();
345
346            // Within the system server, it is an error to access Environment paths without
347            // explicitly specifying a user.
348            Environment.setUserRequired(true);
349
350            // Within the system server, any incoming Bundles should be defused
351            // to avoid throwing BadParcelableException.
352            BaseBundle.setShouldDefuse(true);
353
354            // Ensure binder calls into the system always run at foreground priority.
355            BinderInternal.disableBackgroundScheduling(true);
356
357            // Increase the number of binder threads in system_server
358            BinderInternal.setMaxThreads(sMaxBinderThreads);
359
360            // Prepare the main looper thread (this thread).
361            android.os.Process.setThreadPriority(
362                android.os.Process.THREAD_PRIORITY_FOREGROUND);
363            android.os.Process.setCanSelfBackground(false);
364            Looper.prepareMainLooper();
365
366            // Initialize native services.
367            System.loadLibrary("android_servers");
368
369            // Check whether we failed to shut down last time we tried.
370            // This call may not return.
371            performPendingShutdown();
372
373            // Initialize the system context.
374            createSystemContext();
375
376            // Create the system service manager.
377            mSystemServiceManager = new SystemServiceManager(mSystemContext);
378            mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);
379            LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
380            // Prepare the thread pool for init tasks that can be parallelized
381            SystemServerInitThreadPool.get();
382        } finally {
383            traceEnd();  // InitBeforeStartServices【启动服务前初始化】
384        }
385
386        // Start services.
387        try {
388            traceBeginAndSlog("StartServices");
389            startBootstrapServices();【AMS 这里面创建】
390            startCoreServices();
391            startOtherServices();
392            SystemServerInitThreadPool.shutdown();
393        } catch (Throwable ex) {
394            Slog.e("System", "******************************************");
395            Slog.e("System", "************ Failure starting system services", ex);
396            throw ex;
397        } finally {
398            traceEnd();
399        }
400
401        // For debug builds, log event loop stalls to dropbox for analysis.
402        if (StrictMode.conditionallyEnableDebugLogging()) {
403            Slog.i(TAG, "Enabled StrictMode for system server main thread.");
404        }
405        if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
406            int uptimeMillis = (int) SystemClock.elapsedRealtime();
407            MetricsLogger.histogram(null, "boot_system_server_ready", uptimeMillis);
408            final int MAX_UPTIME_MILLIS = 60 * 1000;
409            if (uptimeMillis > MAX_UPTIME_MILLIS) {
410                Slog.wtf(SYSTEM_SERVER_TIMING_TAG,
411                        "SystemServer init took too long. uptimeMillis=" + uptimeMillis);
412            }
413        }
414
415        // Loop forever.
416        Looper.loop();
417        throw new RuntimeException("Main thread loop unexpectedly exited");
418    }

首先来看SystemServer中关于ActivityManagerService的一些相关的方法。

SystemServer的startBootstrapServices函数

/**
1047       * Starts the small tangle of critical services that are needed to get the system off the
1048       * ground.  These services have complex mutual dependencies which is why we initialize them all
1049       * in one place here.  Unless your service is also entwined in these dependencies, it should be
1050       * initialized in one of the other functions.
1051       */
1052      private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
1053          t.traceBegin("startBootstrapServices");
1054  
1055          // Start the watchdog as early as possible so we can crash the system server
1056          // if we deadlock during early boot
1057          t.traceBegin("StartWatchdog");
1058          final Watchdog watchdog = Watchdog.getInstance();
1059          watchdog.start();
1060          mDumper.addDumpable(watchdog);
1061          t.traceEnd();
1062  
1063          Slog.i(TAG, "Reading configuration...");
1064          final String TAG_SYSTEM_CONFIG = "ReadingSystemConfig";
1065          t.traceBegin(TAG_SYSTEM_CONFIG);
1066          SystemServerInitThreadPool.submit(SystemConfig::getInstance, TAG_SYSTEM_CONFIG);
1067          t.traceEnd();
1068  
1069          // Platform compat service is used by ActivityManagerService, PackageManagerService, and
1070          // possibly others in the future. b/135010838.
1071          t.traceBegin("PlatformCompat");
1072          PlatformCompat platformCompat = new PlatformCompat(mSystemContext);
1073          ServiceManager.addService(Context.PLATFORM_COMPAT_SERVICE, platformCompat);
1074          ServiceManager.addService(Context.PLATFORM_COMPAT_NATIVE_SERVICE,
1075                  new PlatformCompatNative(platformCompat));
1076          AppCompatCallbacks.install(new long[0]);
1077          t.traceEnd();
1078  
1079          // FileIntegrityService responds to requests from apps and the system. It needs to run after
1080          // the source (i.e. keystore) is ready, and before the apps (or the first customer in the
1081          // system) run.
1082          t.traceBegin("StartFileIntegrityService");
1083          mSystemServiceManager.startService(FileIntegrityService.class);
1084          t.traceEnd();
1085  
1086          // Wait for installd to finish starting up so that it has a chance to
1087          // create critical directories such as /data/user with the appropriate
1088          // permissions.  We need this to complete before we initialize other services.
1089          t.traceBegin("StartInstaller");
1090          Installer installer = mSystemServiceManager.startService(Installer.class);
1091          t.traceEnd();
1092  
1093          // In some cases after launching an app we need to access device identifiers,
1094          // therefore register the device identifier policy before the activity manager.
1095          t.traceBegin("DeviceIdentifiersPolicyService");
1096          mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);
1097          t.traceEnd();
1098  
1099          // Uri Grants Manager.
1100          t.traceBegin("UriGrantsManagerService");
1101          mSystemServiceManager.startService(UriGrantsManagerService.Lifecycle.class);
1102          t.traceEnd();
1103  
1104          t.traceBegin("StartPowerStatsService");
1105          // Tracks rail data to be used for power statistics.
1106          mSystemServiceManager.startService(PowerStatsService.class);
1107          t.traceEnd();
1108  
1109          t.traceBegin("StartIStatsService");
1110          startIStatsService();
1111          t.traceEnd();
1112  
1113          // Start MemtrackProxyService before ActivityManager, so that early calls
1114          // to Memtrack::getMemory() don't fail.
1115          t.traceBegin("MemtrackProxyService");
1116          startMemtrackProxyService();
1117          t.traceEnd();
1118  
1119          // Activity manager runs the show.【AMS开始运行】
1120          t.traceBegin("StartActivityManager");
1121          // TODO: Might need to move after migration to WM.
1122          ActivityTaskManagerService atm = mSystemServiceManager.startService(
1123                  ActivityTaskManagerService.Lifecycle.class).getService();//  【1. 创建AMS对象,并启动服务 】
1124          mActivityManagerService = ActivityManagerService.Lifecycle.startService(
1125                  mSystemServiceManager, atm);
1126          mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
1127          mActivityManagerService.setInstaller(installer);
1128          mWindowManagerGlobalLock = atm.getGlobalLock();
1129          t.traceEnd();
1130  
1131          // Data loader manager service needs to be started before package manager
1132          t.traceBegin("StartDataLoaderManagerService");
1133          mDataLoaderManagerService = mSystemServiceManager.startService(
1134                  DataLoaderManagerService.class);
1135          t.traceEnd();
1136  
1137          // Incremental service needs to be started before package manager
1138          t.traceBegin("StartIncrementalService");
1139          mIncrementalServiceHandle = startIncrementalService();
1140          t.traceEnd();
1141  
1142          // Power manager needs to be started early because other services need it.
1143          // Native daemons may be watching for it to be registered so it must be ready
1144          // to handle incoming binder calls immediately (including being able to verify
1145          // the permissions for those calls).
1146          t.traceBegin("StartPowerManager");
1147          mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
1148          t.traceEnd();
1149  
1150          t.traceBegin("StartThermalManager");
1151          mSystemServiceManager.startService(ThermalManagerService.class);
1152          t.traceEnd();
1153  
1154          t.traceBegin("StartHintManager");
1155          mSystemServiceManager.startService(HintManagerService.class);
1156          t.traceEnd();
1157  
1158          // Now that the power manager has been started, let the activity manager
1159          // initialize power management features.
1160          t.traceBegin("InitPowerManagement");
1161          mActivityManagerService.initPowerManagement();
1162          t.traceEnd();
1163  
1164          // Bring up recovery system in case a rescue party needs a reboot
1165          t.traceBegin("StartRecoverySystemService");
1166          mSystemServiceManager.startService(RecoverySystemService.Lifecycle.class);
1167          t.traceEnd();
1168  
1169          // Now that we have the bare essentials of the OS up and running, take
1170          // note that we just booted, which might send out a rescue party if
1171          // we're stuck in a runtime restart loop.
1172          RescueParty.registerHealthObserver(mSystemContext);
1173          PackageWatchdog.getInstance(mSystemContext).noteBoot();
1174  
1175          // Manages LEDs and display backlight so we need it to bring up the display.
1176          t.traceBegin("StartLightsService");
1177          mSystemServiceManager.startService(LightsService.class);
1178          t.traceEnd();
1179  
1180          t.traceBegin("StartDisplayOffloadService");
1181          // Package manager isn't started yet; need to use SysProp not hardware feature
1182          if (SystemProperties.getBoolean("config.enable_display_offload", false)) {
1183              mSystemServiceManager.startService(WEAR_DISPLAYOFFLOAD_SERVICE_CLASS);
1184          }
1185          t.traceEnd();
1186  
1187          t.traceBegin("StartSidekickService");
1188          // Package manager isn't started yet; need to use SysProp not hardware feature
1189          if (SystemProperties.getBoolean("config.enable_sidekick_graphics", false)) {
1190              mSystemServiceManager.startService(WEAR_SIDEKICK_SERVICE_CLASS);
1191          }
1192          t.traceEnd();
1193  
1194          // Display manager is needed to provide display metrics before package manager
1195          // starts up.
1196          t.traceBegin("StartDisplayManager");
1197          mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
1198          t.traceEnd();
1199  
1200          // We need the default display before we can initialize the package manager.
1201          t.traceBegin("WaitForDisplay");
1202          mSystemServiceManager.startBootPhase(t, SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
1203          t.traceEnd();
1204  
1205          // Only run "core" apps if we're encrypting the device.
1206          String cryptState = VoldProperties.decrypt().orElse("");
1207          if (ENCRYPTING_STATE.equals(cryptState)) {
1208              Slog.w(TAG, "Detected encryption in progress - only parsing core apps");
1209              mOnlyCore = true;
1210          } else if (ENCRYPTED_STATE.equals(cryptState)) {
1211              Slog.w(TAG, "Device encrypted - only parsing core apps");
1212              mOnlyCore = true;
1213          }
1214  
1215          // Start the package manager.
1216          if (!mRuntimeRestart) {
1217              FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
1218                      FrameworkStatsLog
1219                              .BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__PACKAGE_MANAGER_INIT_START,
1220                      SystemClock.elapsedRealtime());
1221          }
1222  
1223          t.traceBegin("StartDomainVerificationService");
1224          DomainVerificationService domainVerificationService = new DomainVerificationService(
1225                  mSystemContext, SystemConfig.getInstance(), platformCompat);
1226          mSystemServiceManager.startService(domainVerificationService);
1227          t.traceEnd();
1228  
1229          IPackageManager iPackageManager;
1230          t.traceBegin("StartPackageManagerService");
1231          try {
1232              Watchdog.getInstance().pauseWatchingCurrentThread("packagemanagermain");
1233              Pair<PackageManagerService, IPackageManager> pmsPair = PackageManagerService.main(
1234                      mSystemContext, installer, domainVerificationService,
1235                      mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
1236              mPackageManagerService = pmsPair.first;
1237              iPackageManager = pmsPair.second;
1238          } finally {
1239              Watchdog.getInstance().resumeWatchingCurrentThread("packagemanagermain");
1240          }
1241  
1242          // Now that the package manager has started, register the dex load reporter to capture any
1243          // dex files loaded by system server.
1244          // These dex files will be optimized by the BackgroundDexOptService.
1245          SystemServerDexLoadReporter.configureSystemServerDexReporter(iPackageManager);
1246  
1247          mFirstBoot = mPackageManagerService.isFirstBoot();
1248          mPackageManager = mSystemContext.getPackageManager();
1249          t.traceEnd();
1250          if (!mRuntimeRestart && !isFirstBootOrUpgrade()) {
1251              FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
1252                      FrameworkStatsLog
1253                              .BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__PACKAGE_MANAGER_INIT_READY,
1254                      SystemClock.elapsedRealtime());
1255          }
1256          // Manages A/B OTA dexopting. This is a bootstrap service as we need it to rename
1257          // A/B artifacts after boot, before anything else might touch/need them.
1258          // Note: this isn't needed during decryption (we don't have /data anyways).
1259          if (!mOnlyCore) {
1260              boolean disableOtaDexopt = SystemProperties.getBoolean("config.disable_otadexopt",
1261                      false);
1262              if (!disableOtaDexopt) {
1263                  t.traceBegin("StartOtaDexOptService");
1264                  try {
1265                      Watchdog.getInstance().pauseWatchingCurrentThread("moveab");
1266                      OtaDexoptService.main(mSystemContext, mPackageManagerService);
1267                  } catch (Throwable e) {
1268                      reportWtf("starting OtaDexOptService", e);
1269                  } finally {
1270                      Watchdog.getInstance().resumeWatchingCurrentThread("moveab");
1271                      t.traceEnd();
1272                  }
1273              }
1274          }
1275  
1276          t.traceBegin("StartUserManagerService");
1277          mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
1278          t.traceEnd();
1279  
1280          // Initialize attribute cache used to cache resources from packages.
1281          t.traceBegin("InitAttributerCache");
1282          AttributeCache.init(mSystemContext);
1283          t.traceEnd();
1284  
1285          // Set up the Application instance for the system process and get started.
【为系统进程设置应用程序实例并开始操作。】
1286          t.traceBegin("SetSystemProcess");
1287          mActivityManagerService.setSystemProcess();//  【 2.将AMS所在的系统进程,添加到进程管理中去】
1288          t.traceEnd();
1289  
1290          // The package receiver depends on the activity service in order to get registered.
1291          platformCompat.registerPackageReceiver(mSystemContext);
1292  
1293          // Complete the watchdog setup with an ActivityManager instance and listen for reboots
1294          // Do this only after the ActivityManagerService is properly started as a system process
1295          t.traceBegin("InitWatchdog");
1296          watchdog.init(mSystemContext, mActivityManagerService);
1297          t.traceEnd();
1298  
1299          // DisplayManagerService needs to setup android.display scheduling related policies
1300          // since setSystemProcess() would have overridden policies due to setProcessGroup
1301          mDisplayManagerService.setupSchedulerPolicies();
1302  
1303          // Manages Overlay packages
1304          t.traceBegin("StartOverlayManagerService");
1305          mSystemServiceManager.startService(new OverlayManagerService(mSystemContext));
1306          t.traceEnd();
1307  
1308          // Manages Resources packages
1309          t.traceBegin("StartResourcesManagerService");
1310          ResourcesManagerService resourcesService = new ResourcesManagerService(mSystemContext);
1311          resourcesService.setActivityManagerService(mActivityManagerService);
1312          mSystemServiceManager.startService(resourcesService);
1313          t.traceEnd();
1314  
1315          t.traceBegin("StartSensorPrivacyService");
1316          mSystemServiceManager.startService(new SensorPrivacyService(mSystemContext));
1317          t.traceEnd();
1318  
1319          if (SystemProperties.getInt("persist.sys.displayinset.top", 0) > 0) {
1320              // DisplayManager needs the overlay immediately.
1321              mActivityManagerService.updateSystemUiContext();
1322              LocalServices.getService(DisplayManagerInternal.class).onOverlayChanged();
1323          }
1324  
1325          // The sensor service needs access to package manager service, app ops
1326          // service, and permissions service, therefore we start it after them.
1327          t.traceBegin("StartSensorService");
1328          mSystemServiceManager.startService(SensorService.class);
1329          t.traceEnd();
1330          t.traceEnd(); // startBootstrapServices
1331      }

startOtherServices函数

 /**
676     * Starts a miscellaneous grab bag of stuff that has yet to be refactored
677     * and organized.
678     */
679    private void startOtherServices() {
.......
// The AccountManager must come before the ContentService
779            traceBeginAndSlog("StartAccountManagerService");
780            mSystemServiceManager.startService(ACCOUNT_SERVICE_CLASS);
781            traceEnd();
782
783            traceBeginAndSlog("StartContentService");
784            mSystemServiceManager.startService(CONTENT_SERVICE_CLASS);
785            traceEnd();
786
787            traceBeginAndSlog("InstallSystemProviders");
788            mActivityManagerService.installSystemProviders();// 【3.为系统进程安装ContentProvider对象】
789            traceEnd();
790
791            traceBeginAndSlog("StartVibratorService");
792            vibrator = new VibratorService(context);
793            ServiceManager.addService("vibrator", vibrator);
794            traceEnd();
......

1667        // We now tell the activity manager it is okay to run third party
1668        // code.  It will call back into us once it has gotten to the state
1669        // where third party code can really run (but before it has actually
1670        // started launching the initial applications), for us to complete our
1671        // initialization.
1672        mActivityManagerService.systemReady(() -> {// 【4.在systemReady方法中做善后操作】
1673            Slog.i(TAG, "Making services ready");
1674            traceBeginAndSlog("StartActivityManagerReadyPhase");
1675            mSystemServiceManager.startBootPhase(
1676                    SystemService.PHASE_ACTIVITY_MANAGER_READY);
1677            traceEnd();
1678            traceBeginAndSlog("StartObservingNativeCrashes");
1679            try {
1680                mActivityManagerService.startObservingNativeCrashes();// 【4.1在systemReady方法中做善后操作】
1681            } catch (Throwable e) {
1682                reportWtf("observing native crashes", e);
1683            }
1684            traceEnd();
}

上面的的几个方法就是SystemServer中关于AMS启动时的几个关键方法,主要分为4个步骤

1:创建AMS对象,并启动服务 2:将AMS所在的系统进程,添加到进程管理中去 3:为系统进程安装ContentProvider对象 4:在systemReady方法中做善后操作

image.png

一个一个的来看先这些方法的作用,这些方法就是AMS的启动和初始化过程。

启动ActivityManagerService的方法

 mActivityManagerService = mSystemServiceManager.startService(
522                ActivityManagerService.Lifecycle.class).getService();

AMS服务同样是通过SystemServiceManager来启动的。那我们首先来看ActivityManagerService.Lifecycle的构造方法,然后在来看它的Start函数。

Lifecycle的构造方法中很简单就是构造一个AMS的对象
public Lifecycle(Context context) {
2651            super(context);
2652            mService = new ActivityManagerService(context);
2653        }

创建AMS对象的时候需要传递一个Context作为参数,就是上面创建这个mSystemContext它是系统Context。

接着看AMS的构造方法。

// Note: This method is invoked on the main thread but may need to attach various
2702    // handlers to other threads.  So take care to be explicit about the looper.
2703    public ActivityManagerService(Context systemContext) {
2704        LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
2705        mInjector = new Injector();
2706        mContext = systemContext;// 【系统的context】
2707
2708        mFactoryTest = FactoryTest.getMode();
2709        mSystemThread = ActivityThread.currentActivityThread();//【获得系统的ActivityThread】
2710        mUiContext = mSystemThread.getSystemUiContext();
2711
2712        Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
2713
2714        mPermissionReviewRequired = mContext.getResources().getBoolean(
2715                com.android.internal.R.bool.config_permissionReviewRequired);
2716
2717        mHandlerThread = new ServiceThread(TAG,    //【创建一个HandlerThread用来处理AMS接收的命令】
2718                THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
2719        mHandlerThread.start();
2720        mHandler = new MainHandler(mHandlerThread.getLooper());
2721        mUiHandler = mInjector.getUiHandler(this);
2722
2723        mConstants = new ActivityManagerConstants(this, mHandler);
2724
2725        /* static; one-time init here */
2726        if (sKillHandler == null) {
2727            sKillThread = new ServiceThread(TAG + ":kill",
2728                    THREAD_PRIORITY_BACKGROUND, true /* allowIo */);
2729            sKillThread.start();
2730            sKillHandler = new KillHandler(sKillThread.getLooper());
2731        }
2732
2733        mFgBroadcastQueue = new BroadcastQueue(this, mHandler,// 【初始化广播的队列】
2734                "foreground", BROADCAST_FG_TIMEOUT, false);
2735        mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
2736                "background", BROADCAST_BG_TIMEOUT, true);
2737        mBroadcastQueues[0] = mFgBroadcastQueue;
2738        mBroadcastQueues[1] = mBgBroadcastQueue;
2739
2740        mServices = new ActiveServices(this);// 【初始化Service相关的容器】
2741        mProviderMap = new ProviderMap(this);//【初始化Provider相关的Map,用于保存注册的ContentProvider】
2742        mAppErrors = new AppErrors(mUiContext, this);
2743
2744        // TODO: Move creation of battery stats service outside of activity manager service.
2745        File dataDir = Environment.getDataDirectory();//【初始化并创建 data/system/ 目录】
2746        File systemDir = new File(dataDir, "system");
2747        systemDir.mkdirs();
                         //初始化电量统计服务相关的信息
2748        mBatteryStatsService = new BatteryStatsService(systemContext, systemDir, mHandler);//【电源管理服务】
2749        mBatteryStatsService.getActiveStatistics().readLocked();
2750        mBatteryStatsService.scheduleWriteToDisk();
2751        mOnBattery = DEBUG_POWER ? true
2752                : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
2753        mBatteryStatsService.getActiveStatistics().setCallback(this);
2754          //【初始化系统统计服务,用于统计系统的运行信息】
2755        mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
2756
2757        mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);
2758        mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null,
2759                new IAppOpsCallback.Stub() {
2760                    @Override public void opChanged(int op, int uid, String packageName) {
2761                        if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && packageName != null) {
2762                            if (mAppOpsService.checkOperation(op, uid, packageName)
2763                                    != AppOpsManager.MODE_ALLOWED) {
2764                                runInBackgroundDisabled(uid);
2765                            }
2766                        }
2767                    }
2768                });
2769
2770        mGrantFile = new AtomicFile(new File(systemDir, "urigrants.xml"));
2771
2772        mUserController = new UserController(this);// 【创建系统的第一个user,userID为0,该用户具有管理员权限】
2773
2774        mVrController = new VrController(this);
2775       //   【获取opengle的版本】
2776        GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
2777            ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
2778
2779        if (SystemProperties.getInt("sys.use_fifo_ui", 0) != 0) {
2780            mUseFifoUiScheduling = true;
2781        }
2782
2783        mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
2784        mTempConfig.setToDefaults();
2785        mTempConfig.setLocales(LocaleList.getDefault());  //【初始化字体语言等配置信息】
2786        mConfigurationSeq = mTempConfig.seq = 1;
2787        mStackSupervisor = createStackSupervisor();
2788        mStackSupervisor.onConfigurationChanged(mTempConfig);
2789        mKeyguardController = mStackSupervisor.mKeyguardController;
2790        mCompatModePackages = new CompatModePackages(this, systemDir, mHandler);
2791        mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
2792        mTaskChangeNotificationController =
2793                new TaskChangeNotificationController(this, mStackSupervisor, mHandler);
2794        mActivityStarter = new ActivityStarter(this, mStackSupervisor); //【初始化ActivityStarter,该类是Activity启动和调度的核心类】
2795        mRecentTasks = new RecentTasks(this, mStackSupervisor);
2796
2797        mProcessCpuThread = new Thread("CpuTracker") {
2798            @Override
2799            public void run() {
2800                synchronized (mProcessCpuTracker) {
2801                    mProcessCpuInitLatch.countDown();
2802                    mProcessCpuTracker.init();
2803                }
2804                while (true) {
2805                    try {
2806                        try {
2807                            synchronized(this) {
2808                                final long now = SystemClock.uptimeMillis();
2809                                long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
2810                                long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
2811                                //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
2812                                //        + ", write delay=" + nextWriteDelay);
2813                                if (nextWriteDelay < nextCpuDelay) {
2814                                    nextCpuDelay = nextWriteDelay;
2815                                }
2816                                if (nextCpuDelay > 0) {
2817                                    mProcessCpuMutexFree.set(true);
2818                                    this.wait(nextCpuDelay);
2819                                }
2820                            }
2821                        } catch (InterruptedException e) {
2822                        }
2823                        updateCpuStatsNow();
2824                    } catch (Exception e) {
2825                        Slog.e(TAG, "Unexpected exception collecting process stats", e);
2826                    }
2827                }
2828            }
2829        };
2830
2831        Watchdog.getInstance().addMonitor(this);
2832        Watchdog.getInstance().addThread(mHandler);
2833    }

从代码中可以看出,AMS的构造方法主要是在做一些初始化的先关操作。先保存了自己的运行环境的Context和ActivityThread。AMS负责调度四大组件,所以会初始化broadcast,service和contentProvider相关的变量,接着初始化了电量统计服务,创建了系统的第一个用户,初始化了基本的配置信息,还创建了Activity调度的核心类,因为Activity调度比较复杂,Activity相关的信息初始化会在ActivityStackSupervisor中。

private void start() {
2848        removeAllProcessGroups();
2849        mProcessCpuThread.start();
2850
2851        mBatteryStatsService.publish();
2852        mAppOpsService.publish(mContext);
2853        Slog.d("AppOps", "AppOpsService published");
2854        LocalServices.addService(ActivityManagerInternal.class, new LocalService());//【AMS服务保存到localService中】
2855        // Wait for the synchronized block started in mProcessCpuThread,
2856        // so that any other acccess to mProcessCpuTracker from main thread
2857        // will be blocked during mProcessCpuTracker initialization.
//等待mProcessCpuThread中启动的同步块,
//以便任何其他从主线程访问mProcessCpuTracker
//将在mProcessCpuTracker初始化期间被阻止。
2858        try {
2859            mProcessCpuInitLatch.await();
2860        } catch (InterruptedException e) {
2861            Slog.wtf(TAG, "Interrupted wait during start", e);
2862            Thread.currentThread().interrupt();
2863            throw new IllegalStateException("Interrupted wait during start");
2864        }
2865    }

AMS的start方法很简单,只是启动了几个服务,并把AMS服务自己保存到localService中供程序内部调用。 AMS的构造方法和start方法中做了AMS服务一些变量的初始化和相关服务的初始化。接着看下一个重要的方法setSystemProcess

ActivityManagerService的setSystemProcess方法

public void setSystemProcess() {
2534        try {
                      //【将AMS注册到ServiceManager中】
2535            ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true);
2536            ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);//【注册其他服务到ServiceMananger中】
2537            ServiceManager.addService("meminfo", new MemBinder(this));
2538            ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
2539            ServiceManager.addService("dbinfo", new DbBinder(this));
2540            if (MONITOR_CPU_USAGE) {
2541                ServiceManager.addService("cpuinfo", new CpuBinder(this));
2542            }
2543            ServiceManager.addService("permission", new PermissionController(this));//【注册权限服务到ServiceMananger中】
2544            ServiceManager.addService("processinfo", new ProcessInfoService(this));
2545
2546            ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
2547                    "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);/【从PMS中查询包名为android的application信息】,即framework-res的Application信息
2548            mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());//【将application信息配置到开始创建的activityThread中】
2549
2550            synchronized (this) {//创建了一个ProcessRecord对象,该对象中保存着系统服务的进程信息
2551                ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0);
2552                app.persistent = true;
2553                app.pid = MY_PID;
2554                app.maxAdj = ProcessList.SYSTEM_ADJ;
2555                app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
2556                synchronized (mPidsSelfLocked) {//        【然后将系统进程的processRecord对象也添加到mPidsSelfLocked集合中,和普通应用的进程一样,接收AMS的管理调度】
2557                    mPidsSelfLocked.put(app.pid, app);
2558                }
2559                updateLruProcessLocked(app, false, null);//【更新进程管理的调度信息】
2560                updateOomAdjLocked();
2561            }
2562        } catch (PackageManager.NameNotFoundException e) {
2563            throw new RuntimeException(
2564                    "Unable to find android system package", e);
2565        }
2566    }

在setSystemProcess方法中,首先将自己AMS服务注册到了ServiceManager中,然后又注册了权限服务等其他的系统服务。通过先前创建的Context,得到PMS服务,检索framework-res的Application信息,然后将它配置到系统的ActivityThread中。 为了能让AMS同样可以管理调度系统进程,也创建了一个关于系统进程的ProcessRecord对象,ProcessRecord对象保存一个进程的相关信息。然后将它保存到mPidsSelfLocked集合中方便管理。

AMS具体是如何将检索到的framework-res的application信息,配置到ActivityThread中的,需要继续分析ActivityThread的installSystemApplicationInfo方法。

ActivityThread的 installSystemApplicationInfo函数

public void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) {
2172        synchronized (this) {
2173            getSystemContext().installSystemApplicationInfo(info, classLoader);
2174            getSystemUiContext().installSystemApplicationInfo(info, classLoader);
2175
2176            // give ourselves a default profiler
2177            mProfiler = new Profiler();
2178        }
2179    }

方法中最终调用上面创建的SystemContext的installSystemApplication方法,那就接着看ConxtextImpl的

installSystemApplication方法。

ConxtextImpl 的 installSystemApplication函数

void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) {
2385        mPackageInfo.installSystemApplicationInfo(info, classLoader);
2386    }

最终调用了mPackageInfo的installSystemApplication方法,mPackageInfo就是在创建Context对象的时候传进来的LoadedApk,里面保存了一个应用程序的基本信息

LoadedApk的installSystemApplicationInfo函数、构造方法

/**
209     * Sets application info about the system package.
210     */
211    void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) {
212        assert info.packageName.equals("android");
213        mApplicationInfo = info;
214        mClassLoader = classLoader;
215    }

/**
183       * Create information about the system package.
184       * Must call {@link #installSystemApplicationInfo} later.
185       */
186      LoadedApk(ActivityThread activityThread) {
187          mActivityThread = activityThread;
188          mApplicationInfo = new ApplicationInfo();
189          mApplicationInfo.packageName = "android";
190          mPackageName = "android";
191          mAppDir = null;
192          mResDir = null;
193          mSplitAppDirs = null;
194          mSplitResDirs = null;
195          mOverlayDirs = null;
196          mSharedLibraries = null;
197          mDataDir = null;
198          mDataDirFile = null;
199          mDeviceProtectedDataDirFile = null;
200          mCredentialProtectedDataDirFile = null;
201          mLibDir = null;
202          mBaseClassLoader = null;
203          mSecurityViolation = false;
204          mIncludeCode = true;
205          mRegisterPackage = false;
206          mClassLoader = ClassLoader.getSystemClassLoader();
207          mResources = Resources.getSystem();
208      }
209  

将framework-res.apk的application信息保存到了mApplication变量中。  我们返回去看下第一次创建LoadedApk的时候,使用了一个参数的构造方法,该构造方法中mApplication变量是直接new了一个ApplicationInfo的对象,该applicationInfo并没有指向任何一个应用,为什么开始的时候不直接指定,反而到现在再来重新做一次呢?  这个是因为创建系统进程的context的时候AMS和PMS都还没有起来,那时候没有办法指定它的application,现在AMS,PMS都起来之后再来赋值就可以了。 setSystemProcess主要就是设置系统集成的一些信息,在这里设置了系统进程的Application信息,创建了系统进程的ProcessRecord对象将其保存在进程集合中,方便AMS管理调度。

ActivityManagerService的installSystemProvider方法 Android系统中有很多配置信息都需要保存,这些信息是保存在SettingsProvider中,而这个SettingsProvider也是运行在SystemServer进程中的,由于SystemServer进程依赖SettingsProvider,放在一个进程中可以减少进程间通信的效率损失。

image.png

分析下如何将SettingsProvider.apk也加载到SystemServer进程中。

ActivityManagerService的installSystemProvider函数

 public final void installSystemProviders() {
12131        List<ProviderInfo> providers;
12132        synchronized (this) {//【找到名称为”System”的进程,就是上一步创建的processRecord对象】
12133            ProcessRecord app = mProcessNames.get("system", SYSTEM_UID);
12134            providers = generateApplicationProvidersLocked(app);//【找到所有和system进程相关的ContentProvider】
12135            if (providers != null) {
12136                for (int i=providers.size()-1; i>=0; i--) {
12137                    ProviderInfo pi = (ProviderInfo)providers.get(i);
12138                    if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {//【再次确认进程为system的provider,把不是该进程Provider移除】
12139                        Slog.w(TAG, "Not installing system proc provider " + pi.name
12140                                + ": not system .apk");
12141                        providers.remove(i);
12142                    }
12143                }
12144            }
12145        }
12146        if (providers != null) {
12147            mSystemThread.installSystemProviders(providers);//【把Provider安装到系统的ActivityThread中】
12148        }
12149
12150        mConstants.start(mContext.getContentResolver());
12151        mCoreSettingsObserver = new CoreSettingsObserver(this);
12152        mFontScaleSettingObserver = new FontScaleSettingObserver();
12153
12154        // Now that the settings provider is published we can consider sending
12155        // in a rescue party.
12156        RescueParty.onSettingsProviderPublished(mContext);
12157
12158        //mUsageStatsService.monitorPackages();
12159    }

找到名称为system的进程对象,就是SystemServer进程,然后根据进程对象去查询所有有关的ContentProvider,调用系统进程的主线程ActivityThread安装所有相关的ContentProvider,

installSystemProviders函数中是如何查找相关的contentProvider和如何安装ContentProvider到系统主线程的。需要分析generateApplicationProvidersLocked与installContentProviders方法。

ActivityManagerService的 generateApplicationProvidersLocked函数

private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
11120        List<ProviderInfo> providers = null;
11121        try {//【调用PMS根据进程ID和进程名称来查询Provider】得到Provider
11122            providers = AppGlobals.getPackageManager()
11123                    .queryContentProviders(app.processName, app.uid,
11124                            STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS
11125                                    | MATCH_DEBUG_TRIAGED_MISSING, /*metadastaKey=*/ null)
11126                    .getList();
11127        } catch (RemoteException ex) {
11128        }
11129        if (DEBUG_MU) Slog.v(TAG_MU,
11130                "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
11131        int userId = app.userId;
11132        if (providers != null) {
11133            int N = providers.size();
11134            app.pubProviders.ensureCapacity(N + app.pubProviders.size());
11135            for (int i=0; i<N; i++) {
11136                // TODO: keep logic in sync with installEncryptionUnawareProviders
11137                ProviderInfo cpi =
11138                    (ProviderInfo)providers.get(i);
11139                boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
11140                        cpi.name, cpi.flags);
11141                if (singleton && UserHandle.getUserId(app.uid) != UserHandle.USER_SYSTEM) {
11142                    // This is a singleton provider, but a user besides the
11143                    // default user is asking to initialize a process it runs
11144                    // in...  well, no, it doesn't actually run in this process,
11145                    // it runs in the process of the default user.  Get rid of it.
11146                    providers.remove(i);
11147                    N--;
11148                    i--;
11149                    continue;
11150                }
11151
11152                ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
11153                ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
11154                if (cpr == null) {//【从AMS管理的contentProvider列表中查询对应的】Provider  
11155                    cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);  //【如果AMS的Provider列表中没有对应的Provider实例,就根据查询的provider信息,创建一个对象保存到队列中】
11156                    mProviderMap.putProviderByClass(comp, cpr);
11157                }
11158                if (DEBUG_MU) Slog.v(TAG_MU,
11159                        "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
11160                app.pubProviders.put(cpi.name, cpr);//【同时将provider保存到processRecord对象的pubProviders列表中】
11161                if (!cpi.multiprocess || !"android".equals(cpi.packageName)) {
11162                    // Don't add this if it is a platform component that is marked
11163                    // to run in multiple processes, because this is actually
11164                    // part of the framework so doesn't make sense to track as a
11165                    // separate apk in the process.
11166                    app.addPackage(cpi.applicationInfo.packageName, cpi.applicationInfo.versionCode,
11167                            mProcessStats);
11168                }
11169                notifyPackageUse(cpi.applicationInfo.packageName,
11170                                 PackageManager.NOTIFY_PACKAGE_USE_CONTENT_PROVIDER);
11171            }
11172        }
11173        return providers;
11174    }

这个方法就是从PMS中查询和SystemServer进程相关的Provider,也就是SettingsProvder,然后将它保存到AMS的contentProvider列表中,管理所有的ContentProvder。同时也将它保存到系统进程对象ProcessRecord的变量pubProviders列表中,每个ContentProvider都需要对应到一个进程中去。

如何将SettingsProvider安装到系统的主进程中去。

ActivityThread的installContentProviders函数

private void installContentProviders(
5793            Context context, List<ProviderInfo> providers) {
5794        final ArrayList<ContentProviderHolder> results = new ArrayList<>();
5795
5796        for (ProviderInfo cpi : providers) {
5797            if (DEBUG_PROVIDER) {
5798                StringBuilder buf = new StringBuilder(128);
5799                buf.append("Pub ");
5800                buf.append(cpi.authority);
5801                buf.append(": ");
5802                buf.append(cpi.name);
5803                Log.i(TAG, buf.toString());
5804            }//【通过installProvider方法把provider封装成一个ContentProviderHolder对象,有利于进程间传输】
5805            ContentProviderHolder cph = installProvider(context, null, cpi,
5806                    false /*noisy*/, true /*noReleaseNeeded*/, true /*stable*/);
5807            if (cph != null) {
5808                cph.noReleaseNeeded = true;
5809                results.add(cph);
5810            }
5811        }
5812
5813        try {//【将上面得到的contentProviderHolder对象发布到AMS服务,getApplicationThread代表本地进程的一个binder对象,binder对象可跨进程传输,它在AMS中对应一个ProcessRecord.】
5814            ActivityManager.getService().publishContentProviders(
5815                getApplicationThread(), results);
5816        } catch (RemoteException ex) {
5817            throw ex.rethrowFromSystemServer();
5818        }
5819    }

该方法将得到的contentProvider对象封装成了contentProviderHolder对象,其实就是Binder对象,这样就可以进程间传输了,然后跨进程调用AMS服务注册Provider。AMS负责管理ContentProvider,只有将ContentProvider注册到AMS服务其他进程才能访问。

AMS如何注册Provider。

ActivityManagerService的 publishContentProviders函数

public final void publishContentProviders(IApplicationThread caller,
11939            List<ContentProviderHolder> providers) {
11940        if (providers == null) {
11941            return;
11942        }
11943
11944        enforceNotIsolatedCaller("publishContentProviders");
11945        synchronized (this) {
11946            final ProcessRecord r = getRecordForAppLocked(caller);//【根据调用者的进程得到相应的processRecord对象,就是系统进程的ProcessRecord】
11947            if (DEBUG_MU) Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
11948            if (r == null) {
11949                throw new SecurityException(
11950                        "Unable to find app for caller " + caller
11951                      + " (pid=" + Binder.getCallingPid()
11952                      + ") when publishing content providers");
11953            }
11954
11955            final long origId = Binder.clearCallingIdentity();
11956
11957            final int N = providers.size();
11958            for (int i = 0; i < N; i++) {
11959                ContentProviderHolder src = providers.get(i); //【ActivityThread客户端传过来的provider src(holer)】
11960                if (src == null || src.info == null || src.provider == null) {
11961                    continue;
11962                }
11963                ContentProviderRecord dst = r.pubProviders.get(src.info.name);//根据src provider name得到一开始保存的进程中保存的 【ProciderRecord】
11964                if (DEBUG_MU) Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
11965                if (dst != null) {
11966                    ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
11967                    mProviderMap.putProviderByClass(comp, dst);//【按类将它保存在mProviderMap中】
11968                    String names[] = dst.info.authority.split(";");
11969                    for (int j = 0; j < names.length; j++) {
11970                        mProviderMap.putProviderByName(names[j], dst);//【按authority保存在mProviderMap中】
11971                    }
11972
11973                    int launchingCount = mLaunchingProviders.size();
11974                    int j;
11975                    boolean wasInLaunchingProviders = false;
11976                    for (j = 0; j < launchingCount; j++) {
11977                        if (mLaunchingProviders.get(j) == dst) {
11978                            mLaunchingProviders.remove(j);
11979                            wasInLaunchingProviders = true;
11980                            j--;
11981                            launchingCount--;
11982                        }
11983                    }
11984                    if (wasInLaunchingProviders) {
11985                        mHandler.removeMessages(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG, r);
11986                    }
11987                    synchronized (dst) {
11988                        dst.provider = src.provider;
11989                        dst.proc = r;
11990                        dst.notifyAll();
11991                    }
11992                    updateOomAdjLocked(r, true);
11993                    maybeUpdateProviderUsageStatsLocked(r, src.info.packageName,
11994                            src.info.authority);
11995                }
11996            }
11998            Binder.restoreCallingIdentity(origId);
11999        }
12000    }

AMS的注册服务就是根据参数传过来的provider信息,找到原先进程中pubProviders列表中保存的ContentProviderRecord,然后将它分别以类为key保存在mProviderMap中,和以authority为key保存在mProviderMap中。即AMS提供了多种方案来查找一个ContentProvider,一种是通过authority来查找,一种是指明CompomentName来查找。

installSystemProvider方法的主要工作就是按照普通进程类似的方式,将SettingsProvider注册到系统进程中,方便系统进程对settings的配置数据进行调用

ActivityManagerService的systemReady函数

 public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
14149        traceLog.traceBegin("PhaseActivityManagerReady");
14150        synchronized(this) {
14151            if (mSystemReady) {
14152                // If we're done calling all the receivers, run the next "boot phase" passed in
14153                // by the SystemServer
14154                if (goingCallback != null) {
14155                    goingCallback.run();
14156                }
14157                return;
14158            }
14159//【初始化Doze模式的controller】
14160            mLocalDeviceIdleController
14161                    = LocalServices.getService(DeviceIdleController.LocalService.class);
14162            mAssistUtils = new AssistUtils(mContext);
14163            mVrController.onSystemReady();
14164            // Make sure we have the current profile info, since it is needed for security checks.
14165            mUserController.onSystemReady();
14166            mRecentTasks.onSystemReadyLocked();//【onSystemReadyLocked中 重置RecentTasks】
14167            mAppOpsService.systemReady();
14168            mSystemReady = true;//【设置systemReady为true】
14169        }
14170
14171        try {
14172            sTheRealBuildSerial = IDeviceIdentifiersPolicyService.Stub.asInterface(
14173                    ServiceManager.getService(Context.DEVICE_IDENTIFIERS_SERVICE))
14174                    .getSerial();
14175        } catch (RemoteException e) {}
14176
14177        ArrayList<ProcessRecord> procsToKill = null;
14178        synchronized(mPidsSelfLocked) {//【收集那些在AMS之前启动的进程】
14179            for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
14180                ProcessRecord proc = mPidsSelfLocked.valueAt(i);
14181                if (!isAllowedWhileBooting(proc.info)){
14182                    if (procsToKill == null) {
14183                        procsToKill = new ArrayList<ProcessRecord>();
14184                    }
14185                    procsToKill.add(proc);
14186                }
14187            }
14188        }
14189
14190        synchronized(this) {//【将那些在AMS之前启动的进程杀死,有的进程不能再AMS之前启动】
14191            if (procsToKill != null) {
14192                for (int i=procsToKill.size()-1; i>=0; i--) {
14193                    ProcessRecord proc = procsToKill.get(i);
14194                    Slog.i(TAG, "Removing system update proc: " + proc);
14195                    removeProcessLocked(proc, true, false, "system update done");
14196                }
14197            }
14198
14199            // Now that we have cleaned up any update processes, we
14200            // are ready to start launching real processes and know that
14201            // we won't trample on them any more.
14202            mProcessesReady = true;
14203        }
14204
14205        Slog.i(TAG, "System now ready");
14206        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
14207            SystemClock.uptimeMillis());
14208
14209        synchronized(this) {
14210            // Make sure we have no pre-ready processes sitting around.
14211
14212            if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) {
14213                ResolveInfo ri = mContext.getPackageManager()
14214                        .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
14215                                STOCK_PM_FLAGS);
14216                CharSequence errorMsg = null;
14217                if (ri != null) {
14218                    ActivityInfo ai = ri.activityInfo;
14219                    ApplicationInfo app = ai.applicationInfo;
14220                    if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
14221                        mTopAction = Intent.ACTION_FACTORY_TEST;
14222                        mTopData = null;
14223                        mTopComponent = new ComponentName(app.packageName,
14224                                ai.name);
14225                    } else {
14226                        errorMsg = mContext.getResources().getText(
14227                                com.android.internal.R.string.factorytest_not_system);
14228                    }
14229                } else {
14230                    errorMsg = mContext.getResources().getText(
14231                            com.android.internal.R.string.factorytest_no_action);
14232                }
14233                if (errorMsg != null) {
14234                    mTopAction = null;
14235                    mTopData = null;
14236                    mTopComponent = null;
14237                    Message msg = Message.obtain();
14238                    msg.what = SHOW_FACTORY_ERROR_UI_MSG;
14239                    msg.getData().putCharSequence("msg", errorMsg);
14240                    mUiHandler.sendMessage(msg);
14241                }
14242            }
14243        }
14244
14245        retrieveSettings();//【从settingsProvider的设置总初始化部分变量】
14246        final int currentUserId;
14247        synchronized (this) {
14248            currentUserId = mUserController.getCurrentUserIdLocked();
14249            readGrantedUriPermissionsLocked();
14250        }
14251
14252        if (goingCallback != null) goingCallback.run();//【调用callback方法,该方法在systemServer代码中实现】
14253        traceLog.traceBegin("ActivityManagerStartApps");
14254        mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,
14255                Integer.toString(currentUserId), currentUserId);
14256        mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,
14257                Integer.toString(currentUserId), currentUserId);
14258        mSystemServiceManager.startUser(currentUserId);
14259
14260        synchronized (this) {
14261            // Only start up encryption-aware persistent apps; once user is
14262            // unlocked we'll come back around and start unaware apps
14263            startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE);
14264
14265            // Start up initial activity.
14266            mBooting = true;
14267            // Enable home activity for system user, so that the system can always boot. We don't
14268            // do this when the system user is not setup since the setup wizard should be the one
14269            // to handle home activity in this case.
14270            if (UserManager.isSplitSystemUser() &&
14271                    Settings.Secure.getInt(mContext.getContentResolver(),
14272                         Settings.Secure.USER_SETUP_COMPLETE, 0) != 0) {
14273                ComponentName cName = new ComponentName(mContext, SystemUserHomeActivity.class);
14274                try {//【查询那些persistent为1的application,并启动他们所在的进程】
14275                    AppGlobals.getPackageManager().setComponentEnabledSetting(cName,
14276                            PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0,
14277                            UserHandle.USER_SYSTEM);
14278                } catch (RemoteException e) {
14279                    throw e.rethrowAsRuntimeException();
14280                }
14281            }
14282            startHomeActivityLocked(currentUserId, "systemReady");//【启动HomeActivity,也就是launcher程序】
14283
14284            try {
14285                if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
14286                    Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"
14287                            + " data partition or your device will be unstable.");
14288                    mUiHandler.obtainMessage(SHOW_UID_ERROR_UI_MSG).sendToTarget();
14289                }
14290            } catch (RemoteException e) {
14291            }
14292
14293            if (!Build.isBuildConsistent()) {
14294                Slog.e(TAG, "Build fingerprint is not consistent, warning user");
14295                mUiHandler.obtainMessage(SHOW_FINGERPRINT_ERROR_UI_MSG).sendToTarget();
14296            }
14297
14298            long ident = Binder.clearCallingIdentity();
14299            try {
14300                Intent intent = new Intent(Intent.ACTION_USER_STARTED);
14301                intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14302                        | Intent.FLAG_RECEIVER_FOREGROUND);
14303                intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
14304                broadcastIntentLocked(null, null, intent,
14305                        null, null, 0, null, null, null, AppOpsManager.OP_NONE,
14306                        null, false, false, MY_PID, SYSTEM_UID,
14307                        currentUserId);
14308                intent = new Intent(Intent.ACTION_USER_STARTING);
14309                intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14310                intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
14311                broadcastIntentLocked(null, null, intent,
14312                        null, new IIntentReceiver.Stub() {
14313                            @Override
14314                            public void performReceive(Intent intent, int resultCode, String data,
14315                                    Bundle extras, boolean ordered, boolean sticky, int sendingUser)
14316                                    throws RemoteException {
14317                            }
14318                        }, 0, null, null,
14319                        new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
14320                        null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
14321            } catch (Throwable t) {
14322                Slog.wtf(TAG, "Failed sending first user broadcasts", t);
14323            } finally {
14324                Binder.restoreCallingIdentity(ident);
14325            }
14326            mStackSupervisor.resumeFocusedStackTopActivityLocked();
14327            mUserController.sendUserSwitchBroadcastsLocked(-1, currentUserId);
14328            traceLog.traceEnd(); // ActivityManagerStartApps
14329            traceLog.traceEnd(); // PhaseActivityManagerReady
14330        }
14331    }

SystemReady方法也是比较长,大致可以分为四个部分 第一:在systemReady的时候初始化了deviceIdleController等对象 第二:移除并杀死了那些不该在AMS之前启动的进程 第三:执行了参数传入的回调函数 第四:启动了Launcer界面 第五:启动那些persistent配置为1的进程。

image.png

systemReady参数的回调函数做了什么工作.

try {
                    //ams开始监听native层的crash信息
                    mActivityManagerService.startObservingNativeCrashes();
                } catch (Throwable e) {
                    reportWtf("observing native crashes", e);
                }
                //初始化webVew
                WebViewFactory.prepareWebViewInSystemServer();
 
                try {
                    //启动systemUI
                    startSystemUi(context);
                } catch (Throwable e) {
                    reportWtf("starting System UI", e);
                }
                try {
                    //调用其他服务的systemready方法
                    if (networkScoreF != null) networkScoreF.systemReady();
                } catch (Throwable e) {
                    reportWtf("making Network Score Service ready", e);
                }
……

这个回调函数中主要工作就是启动systemUI并调用其他服务的systemReady方法,SystemReady函数完成了系统就绪的必要的工作,启动了HomeActivity和SystemUI,然后Android系统就全部启动了。 AMS服务启动主要分为几个步骤。

  1. 创建了SystemServer进程的运行环境,包括一个ActivityThread主线程,一个和系统进程相关的Context对象。
  2. 调用AMS的构造方法和start方法,对AMS必要的内容进行初始化
  3. 将函数AMS注册到ServiceManager中,同时对systemServer进程也创建了一个ProcessRecord对象,并设置Context的appliation为framework-res的application对象
  4. 将settingsProvider加载到系统进程systemServer中
  5. 调用systemReady方法做一些启动前的就绪工作,并启动了HomeActivity和SystemUI

·································继续中~~~~~~~~~~~~~~~~~