[안드로이드 프레임워크 시리즈] Chapter 5 AMS 시작 프로세스

1 AMS 소개

AMS(Activity Manager Service), , Android의 업무를 관리하는 회사의 핵심 서비스 입니다 . AndroidQ는 활동을 로 이동했지만 AMS와도 연결되어 있습니다. 일부 시스템 리소스 및 데이터 구조(프로세스, 작업 스택, 네 가지 주요 구성 요소의 수명 주기를 기록하는 상태 시스템 등)를 사용하여 , 네 가지 주요 구성 요소의 수명 주기 관리를 관리합니다. 그 책임은 운영 체제의 프로세스 관리 및 스케줄링 모듈과 유사하므로 에서 매우 중요합니다. 이 글은 Android10(Q)의 소스코드 분석을 바탕으로 작성되었습니다.四大组件的启动切换调度应用进程的管理和调度ActivityTaskManagerService
AMSActivityServiceBroadcastContentProviderAndroid

2 AMS 시작 프로세스

이전 장 [안드로이드 프레임워크 시리즈] 4장 PMS 원리 에서 PMS에 대해 설명했는데, PMS가 앱 부팅/설치 시 APK의 AndroidManifest.xml 파일을 파싱하고 파싱된 결과를 PMS에 캐시한다는 것을 알고 있었습니다.
우리는 또한 AMS아래를 분석합니다.
PMS둘 다 의 시작은 AMSSystemServer 프로세스에 있으며, 시스템이 시작된 후 Zygote进程첫 번째 포크가 종료되고 시작 부팅 서비스로 SystemServer进程들어간 다음 완료됩니다 . Android 시스템의 모든 핵심 서비스가 시작되며 동일 합니다 . 전화기가 켜지면 실행이 시작됩니다. SystemServer가 시작되는 방법에 대해서는 [Android 프레임워크 시리즈] 3장 Zygote 프로세스 관련[Android 차량 시리즈] 10장 시스템 서비스 - SystemServer 소스 코드 분석(API28) 문서를 확인할 수 있습니다.SystemServer:main()->run()->startBootstrapServices() PMS和AMS等核心服务的启动
SystemServerAMSPMSSystemServer

2.1 AMS가 활성화되었습니다

우리는 AMS그것이 SystemServer进程시작되었음을 알고 있습니다. 어떻게 시작되는지 살펴보겠습니다 AMS:
/frameworks/base/services/java/com/android/server/SystemServer.java

348      public static void main(String[] args) {
    
    
349          new SystemServer().run();
350      }
......
370      private void run() {
    
    
......
507          // Start services.
508          try {
    
    
509              traceBeginAndSlog("StartServices");
				 // 引导服务
510              startBootstrapServices();
				 // 核心服务
511              startCoreServices();
				 // 其他服务
512              startOtherServices();
513              SystemServerInitThreadPool.shutdown();
514          } catch (Throwable ex) {
    
    
515              Slog.e("System", "******************************************");
516              Slog.e("System", "************ Failure starting system services", ex);
517              throw ex;
518          } finally {
    
    
519              traceEnd();
520          }
......
543      }

......
623      private void startBootstrapServices() {
    
    
......
658          ActivityTaskManagerService atm = mSystemServiceManager.startService(
659                  ActivityTaskManagerService.Lifecycle.class).getService();
660          mActivityManagerService = ActivityManagerService.Lifecycle.startService(
661                  mSystemServiceManager, atm);
662          mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
663          mActivityManagerService.setInstaller(installer);
664          mWindowManagerGlobalLock = atm.getGlobalLock();
......
779          mActivityManagerService.setSystemProcess();
......
818      }
......
874      /**
875       * Starts a miscellaneous grab bag of stuff that has yet to be refactored and organized.
876       */
877      private void startOtherServices() {
    
    
......
			  // 安装ContentProvider
982           mActivityManagerService.installSystemProviders();
......
1023          wm = WindowManagerService.main(context, inputManager, !mFirstBoot, mOnlyCore,
1024                      new PhoneWindowManager(), mActivityManagerService.mActivityTaskManager);
1025          ServiceManager.addService(Context.WINDOW_SERVICE, wm, /* allowIsolated= */ false,
1026                      DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PROTO);
1027          ServiceManager.addService(Context.INPUT_SERVICE, inputManager,
1028                      /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
			  // WMS与AMS/ATMS关联起来
1032          mActivityManagerService.setWindowManager(wm);
......
			  // 所有的服务已经准备就绪
2035          mActivityManagerService.systemReady(() -> {
    
    
......
				  // 启动阶段500
2038              mSystemServiceManager.startBootPhase(
2039                      SystemService.PHASE_ACTIVITY_MANAGER_READY);
......
2042              try {
    
    
					  // 监测Native Crash
2043                  mActivityManagerService.startObservingNativeCrashes();
2044              } catch (Throwable e) {
    
    
2045                  reportWtf("observing native crashes", e);
2046              }
......
2051              final String WEBVIEW_PREPARATION = "WebViewFactoryPreparation";
2052              Future<?> webviewPrep = null;
2053              if (!mOnlyCore && mWebViewUpdateService != null) {
    
    
2054                  webviewPrep = SystemServerInitThreadPool.get().submit(() -> {
    
    
2055                      Slog.i(TAG, WEBVIEW_PREPARATION);
2056                      TimingsTraceLog traceLog = new TimingsTraceLog(
2057                              SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
2058                      traceLog.traceBegin(WEBVIEW_PREPARATION);
2059                      ConcurrentUtils.waitForFutureNoInterrupt(mZygotePreload, "Zygote preload");
2060                      mZygotePreload = null;
						  // 启动WebView相关
2061                      mWebViewUpdateService.prepareWebViewInSystemServer();
2062                      traceLog.traceEnd();
2063                  }, WEBVIEW_PREPARATION);
2064              }
......
2073              try {
    
    
					  // 启动SystemUi
2074                  startSystemUi(context, windowManagerF);
2075              } catch (Throwable e) {
    
    
2076                  reportWtf("starting System UI", e);
2077              }
......
				  // 启动阶段600
2154              mSystemServiceManager.startBootPhase(
2155                      SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);

......
2249          }, BOOT_TIMINGS_TRACE_LOG);
2250      }

SystemServerAMS두 가지 주요 단계가 시작되고 초기화 됩니다 .

첫 번째 단계 : startBootstrapServices()다음 방법으로 부팅 서비스를 시작합니다.

  1. ActivityTaskManagerService(ATMS)활동 관리를 위한 객체 생성
  2. 객체 생성 AMS및 서비스 시작
  3. AMS현재 시스템을 进程SystemServerAMS 프로세스 관리 시스템에 통합
    setSystemProcess(): SystemServer 프로세스의 LoadedApk에framewok-res.apk 정보를 추가하고 SystemServe 프로세스의 ProcessRecord를 빌드한 후 AMS 프로세스의 통합 관리를 위해 AMS에 저장합니다.

두 번째 단계 : startOtherServices()메서드에서 다른 서비스를 시작합니다.

  1. 시스템 프로세스용 ContentProvider 개체 설치
    installSystemProviders(): SystemServer 프로세스에 SettingsProvider.apk를 설치합니다.
  2. WMS를 초기화하고 AMS 및 ATMS 서비스를 연결합니다.
    setWindowManager()이 방법은 AMS를 WMS와 연결하고 ATMS를 통해 활동을 관리합니다.
  3. AMS 시작이 완료된 후 후속 작업을 완료하도록 서비스 또는 애플리케이션에 알리거나 직접 새 프로세스를 시작합니다.
    AMS.systemReady(): 많은 서비스 또는 애플리케이션 프로세스는 일부 후속 작업을 시작하거나 수행하기 전에 AMS가 시작 작업을 완료할 때까지 기다려야 합니다. AMS는 SystemReady()이러한 대기 중인 서비스 및 애플리케이션 프로세스(예: 데스크탑 시작)를 알리거나 시작하는 프로세스 중입니다.

첫 번째 단계에서는 AMS및 가 생성될 ATMS때 두 메서드가 모두 호출되는 것을 볼 수 있습니다 startService(). 호출 AMS이 생성되고 ActivityManagerService.Lifecycle.startService()생성 ATMSmSystemServiceManager.startService()실제로 ActivityManagerService.Lifecycle.startService()mSystemServiceManager 내부에서 호출되는 서비스의 생성입니다. 아래에서 초기화를 AMS살펴 Lifecycle보겠습니다 AMS.

2.2 AMS 초기화

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

......
2209      public static final class Lifecycle extends SystemService {
    
    
2210          private final ActivityManagerService mService;
2211          private static ActivityTaskManagerService sAtm;
2212  
2213          public Lifecycle(Context context) {
    
    
2214              super(context);
2215              mService = new ActivityManagerService(context, sAtm);
2216          }
2217  
2218          public static ActivityManagerService startService(
2219                  SystemServiceManager ssm, ActivityTaskManagerService atm) {
    
    
2220              sAtm = atm;
2221              return ssm.startService(ActivityManagerService.Lifecycle.class).getService();
2222          }
2223  
2224          @Override
2225          public void onStart() {
    
    
2226              mService.start();
2227          }
2228  
2229          @Override
2230          public void onBootPhase(int phase) {
    
    
2231              mService.mBootPhase = phase;
2232              if (phase == PHASE_SYSTEM_SERVICES_READY) {
    
    
2233                  mService.mBatteryStatsService.systemServicesReady();
2234                  mService.mServices.systemServicesReady();
2235              } else if (phase == PHASE_ACTIVITY_MANAGER_READY) {
    
    
2236                  mService.startBroadcastObservers();
2237              } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
    
    
2238                  mService.mPackageWatchdog.onPackagesReady();
2239              }
2240          }
2241  
2242          @Override
2243          public void onCleanupUser(int userId) {
    
    
2244              mService.mBatteryStatsService.onCleanupUser(userId);
2245          }
2246  
2247          public ActivityManagerService getService() {
    
    
2248              return mService;
2249          }
2250      }
......

ATMS(ActivityTaskManagerService)Android 10에서 도입된 새로운 변경 사항이며 시스템 서비스이기도 합니다 管理Activity启动和调度,包括其容器(task、stacks、displays等). 이번 글은 주로 AMS스타트업에 관한 내용이므로 ActivityTaskManagerService여기서는 자세히 다루지 않겠습니다. Android 10에서는 원래 중심의 관리 및 스케줄링을 중앙으로
옮기고 위치 를 맨 아래에 배치하므로 4가지 주요 구성 요소 중 나머지 3개(서비스, 방송, 콘텐츠 제공자)에 대한 관리 및 스케줄링을 AMS가 담당합니다.AMSactivityATMSframeworks/base/services/core/java/com/android/server/wm/

다음은 의 내부 클래스 Lifecycle입니다 . 최종적으로 반환되는 것은 생성된 개체이며, 위에서도 알고 있듯이 이 개체 도 이러한 방식으로 생성됩니다.AMSActivityManagerService.Lifecycle.startService()mServiceAMSATMS

AMS 생성 프로세스에 대한 간략한 설명:
1.SystemServer: main(), run(), 을 호출 startBootstrapServices()한 후 LifecylestartService() 메서드를 순서대로 호출합니다.
2.Lifecyle: startService()메서드에서 SystemServiceManager호출된 메서드를 startService()Lifecyle.class에 전달합니다.
3.SystemServiceManager: startService()Reflection에 의해Lifecyle 호출되는 메소드 생성 메소드는 Lifecyle객체를 생성한다
4. Lifecyle: AMS생성 메소드에서 호출되는 생성 메소드는 AMS객체를 생성하고 getService()메소드를 통해 AMS 객체를 반환한다.

계속해서 AMS 생성자를 살펴보겠습니다.
/frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

......
2435      public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
    
    
2436          LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
2437          mInjector = new Injector();
			  // 系统上下文,是在SystemServer进程fork出来后通过createSystemContext()创建的,即与SystemServer进程是一一致
2438          mContext = systemContext;
2439  
2440          mFactoryTest = FactoryTest.getMode();
			  // 系统进程的主线程 sCurrentActivityThread,这里是systemMain()中创建的ActivityThread对象。即也与SystemServer一样的。
2441          mSystemThread = ActivityThread.currentActivityThread();
2442          mUiContext = mSystemThread.getSystemUiContext();
2443  
2444          Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
2445  
2446          mHandlerThread = new ServiceThread(TAG,
2447                  THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
2448          mHandlerThread.start();
			  // 处理AMS消息的handler
2449          mHandler = new MainHandler(mHandlerThread.getLooper());
			  // UiHandler对应于Android中的Ui线程
2450          mUiHandler = mInjector.getUiHandler(this);
2451  
2452          mProcStartHandlerThread = new ServiceThread(TAG + ":procStart",
2453                  THREAD_PRIORITY_FOREGROUND, false /* allowIo */);
2454          mProcStartHandlerThread.start();
2455          mProcStartHandler = new Handler(mProcStartHandlerThread.getLooper());
2456  
2457          mConstants = new ActivityManagerConstants(mContext, this, mHandler);
2458          final ActiveUids activeUids = new ActiveUids(this, true /* postChangesToAtm */);
2459          mProcessList.init(this, activeUids);
2460          mLowMemDetector = new LowMemDetector(this);
2461          mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids);
2462  
2463          // Broadcast policy parameters
2464          final BroadcastConstants foreConstants = new BroadcastConstants(
2465                  Settings.Global.BROADCAST_FG_CONSTANTS);
2466          foreConstants.TIMEOUT = BROADCAST_FG_TIMEOUT;
2467  
2468          final BroadcastConstants backConstants = new BroadcastConstants(
2469                  Settings.Global.BROADCAST_BG_CONSTANTS);
2470          backConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
2471  
2472          final BroadcastConstants offloadConstants = new BroadcastConstants(
2473                  Settings.Global.BROADCAST_OFFLOAD_CONSTANTS);
2474          offloadConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
2475          // by default, no "slow" policy in this queue
2476          offloadConstants.SLOW_TIME = Integer.MAX_VALUE;
2477  
2478          mEnableOffloadQueue = SystemProperties.getBoolean(
2479                  "persist.device_config.activity_manager_native_boot.offload_queue_enabled", false);
2480  
			  //创建几种广播相关对象,前台广播、后台广播、offload。
2481          mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
2482                  "foreground", foreConstants, false);
2483          mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
2484                  "background", backConstants, true);
2485          mOffloadBroadcastQueue = new BroadcastQueue(this, mHandler,
2486                  "offload", offloadConstants, true);
2487          mBroadcastQueues[0] = mFgBroadcastQueue;
2488          mBroadcastQueues[1] = mBgBroadcastQueue;
2489          mBroadcastQueues[2] = mOffloadBroadcastQueue;
2490  
			  // 创建ActiveServices对象,管理 ServiceRecord
2491          mServices = new ActiveServices(this);
			  // 创建ProviderMap对象,管理ContentProviderRecord
2492          mProviderMap = new ProviderMap(this);
2493          mPackageWatchdog = PackageWatchdog.getInstance(mUiContext);
2494          mAppErrors = new AppErrors(mUiContext, this, mPackageWatchdog);
2495  
2496          final File systemDir = SystemServiceManager.ensureSystemDir();
2497  
2498          // TODO: Move creation of battery stats service outside of activity manager service.
2499          mBatteryStatsService = new BatteryStatsService(systemContext, systemDir,
2500                  BackgroundThread.get().getHandler());
2501          mBatteryStatsService.getActiveStatistics().readLocked();
2502          mBatteryStatsService.scheduleWriteToDisk();
2503          mOnBattery = DEBUG_POWER ? true
2504                  : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
2505          mBatteryStatsService.getActiveStatistics().setCallback(this);
2506          mOomAdjProfiler.batteryPowerChanged(mOnBattery);
2507  
2508          mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
2509  
2510          mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);
2511  
2512          mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
2513  
2514          mUserController = new UserController(this);
2515  
2516          mPendingIntentController = new PendingIntentController(
2517                  mHandlerThread.getLooper(), mUserController);
2518  
2519          if (SystemProperties.getInt("sys.use_fifo_ui", 0) != 0) {
    
    
2520              mUseFifoUiScheduling = true;
2521          }
2522  
2523          mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
2524          mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
2525  
			  //得到ActivityTaskManagerService的对象,调用ATM.initialize
2526          mActivityTaskManager = atm;
2527          mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController,
2528                  DisplayThread.get().getLooper());
2529          mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);
2530  
2531          mProcessCpuThread = new Thread("CpuTracker") {
    
    
2532              @Override
2533              public void run() {
    
    
2534                  synchronized (mProcessCpuTracker) {
    
    
2535                      mProcessCpuInitLatch.countDown();
2536                      mProcessCpuTracker.init();
2537                  }
2538                  while (true) {
    
    
2539                      try {
    
    
2540                          try {
    
    
2541                              synchronized(this) {
    
    
2542                                  final long now = SystemClock.uptimeMillis();
2543                                  long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
2544                                  long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
2545                                  //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
2546                                  //        + ", write delay=" + nextWriteDelay);
2547                                  if (nextWriteDelay < nextCpuDelay) {
    
    
2548                                      nextCpuDelay = nextWriteDelay;
2549                                  }
2550                                  if (nextCpuDelay > 0) {
    
    
2551                                      mProcessCpuMutexFree.set(true);
2552                                      this.wait(nextCpuDelay);
2553                                  }
2554                              }
2555                          } catch (InterruptedException e) {
    
    
2556                          }
2557                          updateCpuStatsNow();
2558                      } catch (Exception e) {
    
    
2559                          Slog.e(TAG, "Unexpected exception collecting process stats", e);
2560                      }
2561                  }
2562              }
2563          };
2564  
2565          mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext);
2566  
2567          Watchdog.getInstance().addMonitor(this);
2568          Watchdog.getInstance().addThread(mHandler);
2569  
2570          // bind background threads to little cores
2571          // this is expected to fail inside of framework tests because apps can't touch cpusets directly
2572          // make sure we've already adjusted system_server's internal view of itself first
2573          updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
2574          try {
    
    
2575              Process.setThreadGroupAndCpuset(BackgroundThread.get().getThreadId(),
2576                      Process.THREAD_GROUP_SYSTEM);
2577              Process.setThreadGroupAndCpuset(
2578                      mOomAdjuster.mAppCompact.mCompactionThread.getThreadId(),
2579                      Process.THREAD_GROUP_SYSTEM);
2580          } catch (Exception e) {
    
    
2581              Slog.w(TAG, "Setting background thread cpuset failed");
2582          }
2583  
2584      }

AMS의 구축 방법은 주로 초기 폐쇄 작업을 수행하는 것입니다.

  1. 자신만의 런타임 환경을 저장 Context하고ActivityThread
  2. AMS네 가지 주요 구성 요소인 초기화 broadcastservice관련 contentProvider변수의 일정을 담당하고 세 가지 주요 구성 요소(서비스, 브로드캐스트, 공급자)의 관리 및 일정을 담당합니다(활동은 ActivityTaskManagerService로 이동되지만 ActivityTaskManagerService 개체도 여기에 바인딩됨) ,
  3. 그런 다음 메모리, 배터리, 권한(appops.xml에 대해 알아볼 수 있음) 및 성능 관련 개체 또는 변수를 모니터링하도록 초기화됩니다 电量统计服务. mLowMemDetector, mBatteryStatsService, mProcessStats, mAppOpsService, mProcessCpuThread 등 시스템의 첫 번째 사용자를 생성하고 기본 구성 정보를 초기화했습니다.
  4. Activity Scheduling의 핵심 클래스는 Activity Scheduling이 더 복잡하고 Activity 관련 정보의 초기화가 이루어지기 때문에 생성됩니다 ActivityStackSupervisor.

ActivityManagerService의 start() 메서드를 계속 살펴보겠습니다.

2.2.1 ActivityManagerService의 start()

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

2594      private void start() {
    
    
			  // 移除所有的进程组
2595          removeAllProcessGroups();
			  // 启动CPU进程
2596          mProcessCpuThread.start();
2597  
			  // 启动电池状态服务
2598          mBatteryStatsService.publish();
2599          mAppOpsService.publish(mContext);
2600          Slog.d("AppOps", "AppOpsService published");
2601          LocalServices.addService(ActivityManagerInternal.class, new LocalService());
			  // 创建本地服务并注册,将创建的本地服务放入本地服务集合完成注册
2602          mActivityTaskManager.onActivityManagerInternalAdded();
2603          mUgmInternal.onActivityManagerInternalAdded();
2604          mPendingIntentController.onActivityManagerInternalAdded();
2605          // Wait for the synchronized block started in mProcessCpuThread,
2606          // so that any other access to mProcessCpuTracker from main thread
2607          // will be blocked during mProcessCpuTracker initialization.
2608          try {
    
    
				  // 等待mProcessCpuThread完成初始化后,释放锁
2609              mProcessCpuInitLatch.await();
2610          } catch (InterruptedException e) {
    
    
2611              Slog.wtf(TAG, "Interrupted wait during start", e);
2612              Thread.currentThread().interrupt();
2613              throw new IllegalStateException("Interrupted wait during start");
2614          }
2615      }

AMS방법 start()은 매우 간단하며 몇 가지 서비스를 시작하고 프로그램 내부 호출을 AMS위해 서비스 자체를 저장하기만 하면 되며, 구성 방법 및 방법에서는 서비스의 일부 변수에 대한 초기화 및 관련 서비스의 초기화가 수행됩니다 .localService
AMSstart()AMS

그런 다음 다음으로 중요한 메소드인 setSystemProcess를 살펴보세요.

2.2.2 ActivityManagerService의 setSystemProcess() 메소드

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

2040      public void setSystemProcess() {
    
    
2041          try {
    
    
				  // 将AMS注册到ServiceManager中
2042              ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
2043                      DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
				  // 注册进程状态服务
2044              ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
				  // 注册内存Binder
2045              ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false,
2046                      DUMP_FLAG_PRIORITY_HIGH);
				  // 注册图像信息Binder
2047              ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
				  // 注册数据库Binder
2048              ServiceManager.addService("dbinfo", new DbBinder(this));
2049              if (MONITOR_CPU_USAGE) {
    
    
					  // 注册监控CPU使用状态Binder
2050                  ServiceManager.addService("cpuinfo", new CpuBinder(this),
2051                          /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
2052              }
				  // 注册权限控制Binder
2053              ServiceManager.addService("permission", new PermissionController(this));
				  // 注册进程服务Binder
2054              ServiceManager.addService("processinfo", new ProcessInfoService(this));
2055  
				  // 查询并处理ApplicationInfo
2056              ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
2057                      "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
				  // 将Application信息配置到ActivityThread中
2058              mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
2059  
2060              synchronized (this) {
    
    
					  // 创建并处理ProcessRecord
2061                  ProcessRecord app = mProcessList.newProcessRecordLocked(info, info.processName,
2062                          false,
2063                          0,
2064                          new HostingRecord("system"));
2065                  app.setPersistent(true);
2066                  app.pid = MY_PID;
2067                  app.getWindowProcessController().setPid(MY_PID);
2068                  app.maxAdj = ProcessList.SYSTEM_ADJ;
2069                  app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
2070                  mPidsSelfLocked.put(app);
2071                  mProcessList.updateLruProcessLocked(app, false, null);
2072                  updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
2073              }
2074          } catch (PackageManager.NameNotFoundException e) {
    
    
2075              throw new RuntimeException(
2076                      "Unable to find android system package", e);
2077          }
2078  
2079          // Start watching app ops after we and the package manager are up and running.
2080          mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null,
2081                  new IAppOpsCallback.Stub() {
    
    
2082                      @Override public void opChanged(int op, int uid, String packageName) {
    
    
2083                          if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && packageName != null) {
    
    
2084                              if (mAppOpsService.checkOperation(op, uid, packageName)
2085                                      != AppOpsManager.MODE_ALLOWED) {
    
    
2086                                  runInBackgroundDisabled(uid);
2087                              }
2088                          }
2089                      }
2090                  });
2091      }
  1. setSystemProcess()이 방법에서는 먼저 AMS자신의 서비스를 등록한 ServiceManager다음 权限服务等다른 시스템 서비스를 등록합니다.
  2. 이전에 생성된 Context를 통해 PMS서비스를 가져오고 검색한 framework-res的Application信息다음 시스템에 구성합니다 ActivityThread.
  3. 동일한 관리 및 스케줄링 시스템 프로세스를 허용하기 위해 AMS시스템 프로세스에 대한 ProcessRecord객체 도 생성되며 ProcessRecord객체는 프로세스의 관련 정보를 저장합니다.
  4. 그런 다음 쉽게 관리할 수 있도록 저장하세요 mPidsSelfLocked集合.
  5. AMS구체적으로 어떻게 검색 framework-res的application信息하고 구성하는지 , 계속해서 분석 ActivityThread해야 할 방법은 ;ActivityThreadinstallSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader))

ActivityThread 클래스의 메서드를 계속 살펴보겠습니다 installSystemApplicationInfo().

2.2.3 ActivityThread의 installSystemApplicationInfo

/frameworks/base/core/java/android/app/ActivityThread.java

2417      public void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) {
    
    
2418          synchronized (this) {
    
    
2419              getSystemContext().installSystemApplicationInfo(info, classLoader);
2420              getSystemUiContext().installSystemApplicationInfo(info, classLoader);
2421  
2422              // give ourselves a default profiler
2423              mProfiler = new Profiler();
2424          }
2425      }

이 메서드에서는 위에서 생성한 SystemContext 및 SystemUiContext의 메서드가 최종적으로 호출됩니다 installSystemApplicationInfo(). 그런 다음 ContextImpl의 메소드를
살펴보십시오 .installSystemApplicationInfo()

/frameworks/base/core/java/android/app/ContextImpl.java

......
2427      /**
2428       * System Context to be used for UI. This Context has resources that can be themed.
2429       * Make sure that the created system UI context shares the same LoadedApk as the system context.
2430       * @param systemContext The system context which created by
2431       *                      {@link #createSystemContext(ActivityThread)}.
2432       * @param displayId The ID of the display where the UI is shown.
2433       */
2434      static ContextImpl createSystemUiContext(ContextImpl systemContext, int displayId) {
    
    
2435          final LoadedApk packageInfo = systemContext.mPackageInfo;
2436          ContextImpl context = new ContextImpl(null, systemContext.mMainThread, packageInfo, null,
2437                  null, null, 0, null, null);
2438          context.setResources(createResources(null, packageInfo, null, displayId, null,
2439                  packageInfo.getCompatibilityInfo()));
2440          context.updateDisplay(displayId);
2441          return context;
2442      }
2443  
2444      /**
2445       * The overloaded method of {@link #createSystemUiContext(ContextImpl, int)}.
2446       * Uses {@Code Display.DEFAULT_DISPLAY} as the target display.
2447       */
2448      static ContextImpl createSystemUiContext(ContextImpl systemContext) {
    
    
2449          return createSystemUiContext(systemContext, Display.DEFAULT_DISPLAY);
2450      }
......
2581      void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) {
    
    
2582          mPackageInfo.installSystemApplicationInfo(info, classLoader);
2583      }
......

mPackageInfo최종적으로 호출 되는 메소드는 다음 과 같습니다 installSystemApplication().
/frameworks/base/core/java/android/app/LoadedApk.java

240      /**
241       * Sets application info about the system package.
242       */
243      void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) {
    
    
244          assert info.packageName.equals("android");
245          mApplicationInfo = info;
246          mDefaultClassLoader = classLoader;
247          mAppComponentFactory = createAppFactory(info, mDefaultClassLoader);
248          mClassLoader = mAppComponentFactory.instantiateClassLoader(mDefaultClassLoader,
249                  new ApplicationInfo(mApplicationInfo));
250      }

mPackageInfoContext 객체 생성 시 전달되며 LoadedApk, 애플리케이션의 기본 정보가 저장되며,
setSystemProcess()주로 시스템 프로세스의 애플리케이션 정보를 설정하는 시스템 통합을 위한 일부 정보를 설정하는 역할을 하며, 시스템 프로세스가 생성되어 ProcessRecord저장됩니다. 프로세스 모음에서는 AMS관리 및 예약이 편리합니다.

이 시점에서 1단계 방법 startBootstrapServices()의 시작 부팅 서비스 초기화가 완료되었으며 다음에는 다른 서비스를 시작하기 위한 2단계 방법의 쌍 초기화에 AMS대해 계속 살펴보겠습니다startOtherServices()AMS .

위의 startOtherServices()메소드에서 호출되는 메소드를 볼 수 있습니다 AMS. installSystemProviders()이 메소드가 수행하는 작업을 확인해 보겠습니다.

2.2.4 ActivityManagerService의 installSystemProviders

ActivityManagerService방법 installSystemProviders()
안드로이드 시스템에는 저장해야 할 많은 구성 정보가 있는데, 이 정보들은 에 저장되어 있고 SettingsProvider이것도 SettingsProvider에서 실행되고 있는데 , 종속성 SystemServer进程으로 인해 프로세스에 넣어두면 인터의 효율성 손실을 줄일 수 있다. -프로세스 통신; 아래에서 분석해 보겠습니다. 다음은 /frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java 에도 로드되는 방법입니다.SystemServer进程SettingsProvider
SettingsProvider.apkSystemServer进程

7543      public final void installSystemProviders() {
    
    
7544          List<ProviderInfo> providers;
7545          synchronized (this) {
    
    
				  // 找到名为"system"的进程,就是setSystemProcess中创建的ProcessRecord对象
7546              ProcessRecord app = mProcessList.mProcessNames.get("system", SYSTEM_UID);
7547              providers = generateApplicationProvidersLocked(app);
7548              if (providers != null) {
    
    
7549                  for (int i=providers.size()-1; i>=0; i--) {
    
    
7550                      ProviderInfo pi = (ProviderInfo)providers.get(i);
7551                      if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
    
    
7552                          Slog.w(TAG, "Not installing system proc provider " + pi.name
7553                                  + ": not system .apk");
							  // 移除非系统provider
7554                          providers.remove(i);
7555                      }
7556                  }
7557              }
7558          }
7559          if (providers != null) {
    
    
				  // 安装所有的系统provider
7560              mSystemThread.installSystemProviders(providers);
7561          }
7562  
7563          synchronized (this) {
    
    
7564              mSystemProvidersInstalled = true;
7565          }
7566          mConstants.start(mContext.getContentResolver());
			  // 创建核心Settings Observer,用于监听Settings的改变
7567          mCoreSettingsObserver = new CoreSettingsObserver(this);
7568          mActivityTaskManager.installSystemProviders();
			  // 开发者权限
7569          mDevelopmentSettingsObserver = new DevelopmentSettingsObserver();
7570          SettingsToPropertiesMapper.start(mContext.getContentResolver());
7571          mOomAdjuster.initSettings();
7572  
7573          // Now that the settings provider is published we can consider sending
7574          // in a rescue party.
7575          RescueParty.onSettingsProviderPublished(mContext);
7576  
7577          //mUsageStatsService.monitorPackages();
7578      }

즉, 명명된 프로세스 개체를 찾은 system다음 SystemServer进程프로세스 개체에 따라 관련된 모든 개체를 쿼리하고 ContentProvider시스템 프로세스의 메인 스레드를 호출하여 ActivityThread관련된 모든 개체를 설치합니다 ContentProvider. 특히 관련 개체를 찾는 방법 과 메인 스레드에 ContentProvider설치하는 방법을 설명합니다. ContentProvider시스템의.

generateApplicationProvidersLocked()기능: ProviderInfo 목록을 반환합니다.
installSystemProviders()기능: ActivityThread는 프로세스의 Android 운영 환경으로 간주할 수 있으므로 이 메서드는 프로세스용으로 설치된다는 의미입니다 ContentProvider.
그런 다음 다음 두 가지 방법을 분석하십시오.

2.2.5 ActivityManagerService의 generateApplicationProvidersLocked()

generateApplicationProvidersLocked()먼저 메소드를 살펴보세요 :
/frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

......
6409      private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
    
    
6410          List<ProviderInfo> providers = null;
6411          try {
    
    
				  // 向PMS查询满足要求的ProviderInfo,最重要的查询条件包括:进程名和进程uid
6412              providers = AppGlobals.getPackageManager()
6413                      .queryContentProviders(app.processName, app.uid,
6414                              STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS
6415                                      | MATCH_DEBUG_TRIAGED_MISSING, /*metadastaKey=*/ null)
6416                      .getList();
6417          } catch (RemoteException ex) {
    
    
6418          }
6419          if (DEBUG_MU) Slog.v(TAG_MU,
6420                  "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6421          int userId = app.userId;
6422          if (providers != null) {
    
    
6423              int N = providers.size();
6424              app.pubProviders.ensureCapacity(N + app.pubProviders.size());
6425              for (int i=0; i<N; i++) {
    
    
......
					  // AMS对ContentProvider的管理
6427                  ProviderInfo cpi =
6428                      (ProviderInfo)providers.get(i);
6429                  boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6430                          cpi.name, cpi.flags);
6431                  if (singleton && UserHandle.getUserId(app.uid) != UserHandle.USER_SYSTEM) {
    
    
6432                      // This is a singleton provider, but a user besides the
6433                      // default user is asking to initialize a process it runs
6434                      // in...  well, no, it doesn't actually run in this process,
6435                      // it runs in the process of the default user.  Get rid of it.
6436                      providers.remove(i);
6437                      N--;
6438                      i--;
6439                      continue;
6440                  }
6441  
6442                  ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
6443                  ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
6444                  if (cpr == null) {
    
    
						  // ContentProvider在AMS中用ContentProviderRecord来表示
6445                      cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);
						  // 保存到AMS的mProvidersByClass中
6446                      mProviderMap.putProviderByClass(comp, cpr);
6447                  }
6448                  if (DEBUG_MU) Slog.v(TAG_MU,
6449                          "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
					  // 将信息也保存到ProcessRecord中
6450                  app.pubProviders.put(cpi.name, cpr);
6451                  if (!cpi.multiprocess || !"android".equals(cpi.packageName)) {
    
    
......
						  // 保存PackageName到ProcessRecord中
6456                      app.addPackage(cpi.applicationInfo.packageName,
6457                              cpi.applicationInfo.longVersionCode, mProcessStats);
6458                  }
6459                  notifyPackageUse(cpi.applicationInfo.packageName,
6460                                   PackageManager.NOTIFY_PACKAGE_USE_CONTENT_PROVIDER);
6461              }
6462          }
6463          return providers;
6464      }
  1. 방법 PMS은 그것 , 즉 그것 으로부터 질의하고 SystemServer进程상호 연관시킨 다음 그것을 목록에 저장하는 것 입니다 .ProviderSettingsProvderAMSContentProvider
  2. 동시에 시스템 프로세스 객체 ProcessRecord의 변수 목록 에도 저장되는데, 이는 모두 관리해야 하기 때문에 목록 pubProviders저장 됩니다 .AMSproviderAMSContentProvder
  3. pubProviders각각은 ContentProvider프로세스에 대응해야 하므로 프로세스 개체 목록에 저장합니다 .

2.2.6 ActivityThread의 installSystemProviders()

SettingsProvider그런 다음 시스템의 기본 프로세스에 설치하는 방법을 확인하세요 .

/frameworks/base/core/java/android/app/ActivityThread.java

......
6515      private void installContentProviders(
6516              Context context, List<ProviderInfo> providers) {
    
    
6517          final ArrayList<ContentProviderHolder> results = new ArrayList<>();
6518  
6519          for (ProviderInfo cpi : providers) {
    
    
6520              if (DEBUG_PROVIDER) {
    
    
6521                  StringBuilder buf = new StringBuilder(128);
6522                  buf.append("Pub ");
6523                  buf.append(cpi.authority);
6524                  buf.append(": ");
6525                  buf.append(cpi.name);
6526                  Log.i(TAG, buf.toString());
6527              }
				  // 调用installProvider函数,得到一个ContentProviderHolder对象
6528              ContentProviderHolder cph = installProvider(context, null, cpi,
6529                      false /*noisy*/, true /*noReleaseNeeded*/, true /*stable*/);
6530              if (cph != null) {
    
    
6531                  cph.noReleaseNeeded = true;
					  // 将返回的cph保存到results数组中
6532                  results.add(cph);
6533              }
6534          }
6535  
6536          try {
    
    
				  // 调用AMS的publishContentProviders注册这些ContentProvider
6537              ActivityManager.getService().publishContentProviders(
6538                  getApplicationThread(), results);
6539          } catch (RemoteException ex) {
    
    
6540              throw ex.rethrowFromSystemServer();
6541          }
6542      }
......
7167      public final void installSystemProviders(List<ProviderInfo> providers) {
    
    
7168          if (providers != null) {
    
    
7169              installContentProviders(mInitialApplication, providers);
7170          }
7171      }
  1. 이 방법은 획득한 객체를 실제로 객체인 객체 ContentProvder로 캡슐화하여 프로세스 간에 전송할 수 있도록 한 다음 프로세스 간 서비스 등록을 호출합니다 .contentProviderHolderBinderAMSProvider
  2. AMS관리를 담당하며 서비스 에 등록 ContentProvider할 다른 프로세스만 액세스할 수 있습니다.ContentProviderAMS

그런 다음 AMS등록 방법을 확인하세요 Provider.

2.2.7 ActivityManagerService의PublishContentProviders()는 Provider를 등록합니다.

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

7342  
7343      public final void publishContentProviders(IApplicationThread caller,
7344              List<ContentProviderHolder> providers) {
    
    
7345          if (providers == null) {
    
    
7346              return;
7347          }
7348  
7349          enforceNotIsolatedCaller("publishContentProviders");
7350          synchronized (this) {
    
    
7351              final ProcessRecord r = getRecordForAppLocked(caller);
7352              if (DEBUG_MU) Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
7353              if (r == null) {
    
    
7354                  throw new SecurityException(
7355                          "Unable to find app for caller " + caller
7356                        + " (pid=" + Binder.getCallingPid()
7357                        + ") when publishing content providers");
7358              }
7359  
7360              final long origId = Binder.clearCallingIdentity();
7361  
7362              final int N = providers.size();
7363              for (int i = 0; i < N; i++) {
    
    
7364                  ContentProviderHolder src = providers.get(i);
7365                  if (src == null || src.info == null || src.provider == null) {
    
    
7366                      continue;
7367                  }
7368                  ContentProviderRecord dst = r.pubProviders.get(src.info.name);
7369                  if (DEBUG_MU) Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
7370                  if (dst != null) {
    
    
7371                      ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
7372                      mProviderMap.putProviderByClass(comp, dst);
7373                      String names[] = dst.info.authority.split(";");
7374                      for (int j = 0; j < names.length; j++) {
    
    
7375                          mProviderMap.putProviderByName(names[j], dst);
7376                      }
7377  
7378                      int launchingCount = mLaunchingProviders.size();
7379                      int j;
7380                      boolean wasInLaunchingProviders = false;
7381                      for (j = 0; j < launchingCount; j++) {
    
    
7382                          if (mLaunchingProviders.get(j) == dst) {
    
    
7383                              mLaunchingProviders.remove(j);
7384                              wasInLaunchingProviders = true;
7385                              j--;
7386                              launchingCount--;
7387                          }
7388                      }
7389                      if (wasInLaunchingProviders) {
    
    
7390                          mHandler.removeMessages(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG, r);
7391                      }
7392                      // Make sure the package is associated with the process.
7393                      // XXX We shouldn't need to do this, since we have added the package
7394                      // when we generated the providers in generateApplicationProvidersLocked().
7395                      // But for some reason in some cases we get here with the package no longer
7396                      // added...  for now just patch it in to make things happy.
7397                      r.addPackage(dst.info.applicationInfo.packageName,
7398                              dst.info.applicationInfo.longVersionCode, mProcessStats);
7399                      synchronized (dst) {
    
    
7400                          dst.provider = src.provider;
7401                          dst.setProcess(r);
7402                          dst.notifyAll();
7403                      }
7404                      updateOomAdjLocked(r, true, OomAdjuster.OOM_ADJ_REASON_GET_PROVIDER);
7405                      maybeUpdateProviderUsageStatsLocked(r, src.info.packageName,
7406                              src.info.authority);
7407                  }
7408              }
7409  
7410              Binder.restoreCallingIdentity(origId);
7411          }
7412      }
  1. AMS등록 서비스는 매개변수로 전달 된 정보에 따라 원래 프로세스 목록에 저장된 provider정보를 찾아 클래스로 저장 하는 것입니다 .pubProvidersContentProviderRecordkeymProviderMapauthoritykeymProviderMap
  2. 즉, AMS하나를 찾기 위해 다양한 솔루션이 제공되는데 ContentProvider, 하나는 authority통해 찾기, 다른 하나는 CompomentName찾기 위해 지정하는 것입니다.
  3. 이때는 중간 SettingsProvider에 position one이 공식적으로 등록되어 있으므로 일반적인 프로세스와 유사한 방법으로 시스템 프로세스에 등록하여 시스템 프로세스가 호출할 수 있도록 하는 것이 메소드의 주요 작업임을 SystemServer进程알 수 있다. 구성 데이터installSystemProviderSettingsProvidersettings

startOtherServices()계속해서 내려가는 2단계 방법을 살펴보겠습니다 . 매우 중요한 방법이 있습니다.systemReady()

2.2.8 ActivityManagerService의 시스템 준비

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

8967  
8968      public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
    
    
8969          traceLog.traceBegin("PhaseActivityManagerReady");
8970          synchronized(this) {
    
    
				  // 第一次进入mSystemReady为false
8971              if (mSystemReady) {
    
    
8972                  // If we're done calling all the receivers, run the next "boot phase" passed in
8973                  // by the SystemServer
8974                  if (goingCallback != null) {
    
    
8975                      goingCallback.run();
8976                  }
8977                  return;
8978              }
8979  
				  // 关键服务等待systemReady,继续完成一些初始化或进一步的工作
8980              mLocalDeviceIdleController
8981                      = LocalServices.getService(DeviceIdleController.LocalService.class);
				  // 调用各种服务的Ready方法
8982              mActivityTaskManager.onSystemReady();
8983              // Make sure we have the current profile info, since it is needed for security checks.
8984              mUserController.onSystemReady();
8985              mAppOpsService.systemReady();
8986              mSystemReady = true;
8987          }
8988  
8989          try {
    
    
				  //获取设备识别字符串
8990              sTheRealBuildSerial = IDeviceIdentifiersPolicyService.Stub.asInterface(
8991                      ServiceManager.getService(Context.DEVICE_IDENTIFIERS_SERVICE))
8992                      .getSerial();
8993          } catch (RemoteException e) {
    
    }
8994  
			  // 收集目前已经存在的进程(mPidsSelfLocked中保留了当前正在运行的所有进程信息)
8995          ArrayList<ProcessRecord> procsToKill = null;
8996          synchronized(mPidsSelfLocked) {
    
    
8997              for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
    
    
8998                  ProcessRecord proc = mPidsSelfLocked.valueAt(i);
					  // 已启动的进程,若进程没有FLAG_PERSISTENT标志,则会被加入到procsToKill中
8999                  if (!isAllowedWhileBooting(proc.info)){
    
    
9000                      if (procsToKill == null) {
    
    
9001                          procsToKill = new ArrayList<ProcessRecord>();
9002                      }
9003                      procsToKill.add(proc);
9004                  }
9005              }
9006          }
9007  
			  // 销毁在AMS启动之前存在的进程(关闭procsToKill中的所有进程)
9008          synchronized(this) {
    
    
9009              if (procsToKill != null) {
    
    
9010                  for (int i=procsToKill.size()-1; i>=0; i--) {
    
    
9011                      ProcessRecord proc = procsToKill.get(i);
9012                      Slog.i(TAG, "Removing system update proc: " + proc);
9013                      mProcessList.removeProcessLocked(proc, true, false, "system update done");
9014                  }
9015              }
9016  
9017              // Now that we have cleaned up any update processes, we
9018              // are ready to start launching real processes and know that
9019              // we won't trample on them any more.
				  // 到这里系统准备完毕
9020              mProcessesReady = true;
9021          }
9022  
9023          Slog.i(TAG, "System now ready");
9024          EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY, SystemClock.uptimeMillis());
9025  
9026          mAtmInternal.updateTopComponentForFactoryTest();
9027          mAtmInternal.getLaunchObserverRegistry().registerLaunchObserver(mActivityLaunchObserver);
9028  
9029          watchDeviceProvisioning(mContext);
9030  
			  // 初始化Settings变量
9031          retrieveSettings();
9032          mUgmInternal.onSystemReady();
9033  
9034          final PowerManagerInternal pmi = LocalServices.getService(PowerManagerInternal.class);
9035          if (pmi != null) {
    
    
9036              pmi.registerLowPowerModeObserver(ServiceType.FORCE_BACKGROUND_CHECK,
9037                      state -> updateForceBackgroundCheck(state.batterySaverEnabled));
9038              updateForceBackgroundCheck(
9039                      pmi.getLowPowerState(ServiceType.FORCE_BACKGROUND_CHECK).batterySaverEnabled);
9040          } else {
    
    
9041              Slog.wtf(TAG, "PowerManagerInternal not found.");
9042          }
9043  
			  // 运行goingCallback,SystemServer调用时传入的
9044          if (goingCallback != null) goingCallback.run();
9045          // Check the current user here as a user can be started inside goingCallback.run() from
9046          // other system services.
9047          final int currentUserId = mUserController.getCurrentUserId();
9048          Slog.i(TAG, "Current user:" + currentUserId);
			  // 获取UserId
9049          if (currentUserId != UserHandle.USER_SYSTEM && !mUserController.isSystemUserStarted()) {
    
    
9050              // User other than system user has started. Make sure that system user is already
9051              // started before switching user.
9052              throw new RuntimeException("System user not started while current user is:"
9053                      + currentUserId);
9054          }
9055          traceLog.traceBegin("ActivityManagerStartApps");
			  // 给BatteryStatsService发送状态
9056          mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,
9057                  Integer.toString(currentUserId), currentUserId);
9058          mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,
9059                  Integer.toString(currentUserId), currentUserId);
			  // SystemServiceManager设置UserId
9060          mSystemServiceManager.startUser(currentUserId);
9061  
9062          synchronized (this) {
    
    
9063              // Only start up encryption-aware persistent apps; once user is
9064              // unlocked we'll come back around and start unaware apps
9065              startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE);
9066  
9067              // Start up initial activity.
9068              mBooting = true;
9069              // Enable home activity for system user, so that the system can always boot. We don't
9070              // do this when the system user is not setup since the setup wizard should be the one
9071              // to handle home activity in this case.
9072              if (UserManager.isSplitSystemUser() &&
9073                      Settings.Secure.getInt(mContext.getContentResolver(),
9074                           Settings.Secure.USER_SETUP_COMPLETE, 0) != 0) {
    
    
9075                  ComponentName cName = new ComponentName(mContext, SystemUserHomeActivity.class);
9076                  try {
    
    
9077                      AppGlobals.getPackageManager().setComponentEnabledSetting(cName,
9078                              PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0,
9079                              UserHandle.USER_SYSTEM);
9080                  } catch (RemoteException e) {
    
    
9081                      throw e.rethrowAsRuntimeException();
9082                  }
9083              }
				  // 调用ActivityTaskManagerService的startHomeOnAllDisplays方法(就是启动Launcher的Activity)
9084              mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");
9085  
9086              mAtmInternal.showSystemReadyErrorDialogsIfNeeded();
9087  
9088              final int callingUid = Binder.getCallingUid();
9089              final int callingPid = Binder.getCallingPid();
9090              long ident = Binder.clearCallingIdentity();
9091              try {
    
    
					  // 发送一些广播ACTION_USER_STARTED 和 ACTION_USER_STARTING
9092                  Intent intent = new Intent(Intent.ACTION_USER_STARTED);
9093                  intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
9094                          | Intent.FLAG_RECEIVER_FOREGROUND);
9095                  intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
9096                  broadcastIntentLocked(null, null, intent,
9097                          null, null, 0, null, null, null, OP_NONE,
9098                          null, false, false, MY_PID, SYSTEM_UID, callingUid, callingPid,
9099                          currentUserId);
9100                  intent = new Intent(Intent.ACTION_USER_STARTING);
9101                  intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
9102                  intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
9103                  broadcastIntentLocked(null, null, intent,
9104                          null, new IIntentReceiver.Stub() {
    
    
9105                              @Override
9106                              public void performReceive(Intent intent, int resultCode, String data,
9107                                      Bundle extras, boolean ordered, boolean sticky, int sendingUser)
9108                                      throws RemoteException {
    
    
9109                              }
9110                          }, 0, null, null,
9111                          new String[] {
    
    INTERACT_ACROSS_USERS}, OP_NONE,
9112                          null, true, false, MY_PID, SYSTEM_UID, callingUid, callingPid,
9113                          UserHandle.USER_ALL);
9114              } catch (Throwable t) {
    
    
9115                  Slog.wtf(TAG, "Failed sending first user broadcasts", t);
9116              } finally {
    
    
9117                  Binder.restoreCallingIdentity(ident);
9118              }
9119              mAtmInternal.resumeTopActivities(false /* scheduleIdle */);
9120              mUserController.sendUserSwitchBroadcasts(-1, currentUserId);
9121  
9122              BinderInternal.nSetBinderProxyCountWatermarks(BINDER_PROXY_HIGH_WATERMARK,
9123                      BINDER_PROXY_LOW_WATERMARK);
9124              BinderInternal.nSetBinderProxyCountEnabled(true);
9125              BinderInternal.setBinderProxyCountCallback(
9126                      new BinderInternal.BinderProxyLimitListener() {
    
    
9127                          @Override
9128                          public void onLimitReached(int uid) {
    
    
9129                              Slog.wtf(TAG, "Uid " + uid + " sent too many Binders to uid "
9130                                      + Process.myUid());
9131                              BinderProxy.dumpProxyDebugInfo();
9132                              if (uid == Process.SYSTEM_UID) {
    
    
9133                                  Slog.i(TAG, "Skipping kill (uid is SYSTEM)");
9134                              } else {
    
    
9135                                  killUid(UserHandle.getAppId(uid), UserHandle.getUserId(uid),
9136                                          "Too many Binders sent to SYSTEM");
9137                              }
9138                          }
9139                      }, mHandler);
9140  
9141              traceLog.traceEnd(); // ActivityManagerStartApps
9142              traceLog.traceEnd(); // PhaseActivityManagerReady
9143          }
9144      }

systemReady()이 방법은 상대적으로 길며 대략 다음과 같이 나눌 수 있습니다.

  1. etc 객체는 다음에서 systemReady()초기화됩니다.deviceIdleController
  2. AMS 이전에 시작하면 안 되는 프로세스를 제거하고 종료합니다(FLAG_PERSISTENT 플래그가 없는 프로세스는 종료됩니다).
  3. GoingCallback을 실행하고 매개변수로 전달된 콜백 함수를 실행합니다.
  4. Launcher, 즉 데스크톱 애플리케이션의 활동을 시작합니다.
  5. 영구 구성이 1인 프로세스를 시작합니다.

위의 내용을 통해 SystemServer메소드 가 콜백된 후 몇 가지 논리도 수행한다는 startOtherServices()것을 알 수 있습니다 . 콜백 함수는 다음 작업을 수행합니다.systemReady()

  1. 가장 중요한 것은 systemUI를 시작하고 다른 서비스의 systemReady 메서드를 호출하는 것입니다.
  2. SystemReady 기능은 시스템 준비에 필요한 작업을 완료합니다.
  3. HomeActivity 및 SystemUI 시작됨
  4. 그러면 Android 시스템이 모두 시작됩니다.

3개 요약

여기에 AMS의 시작을 요약해 보겠습니다.

  1. 시스템 시작 후 Zygote进程첫 번째 포크SystemServer进程
  2. SystemServer->run()->createSystemContext(): 시스템의 객체, 운영 환경을 생성
    합니다 .ActivityThreadmSystemContextsystemUiContext
  3. SystemServer->run()->startBootstrapServices()->ActivityManagerService.Lifecycle.startService():
    부트 서비스 시작 방법에서 AMS는 생성자를 통해 일부 개체 ( new ActivityManagerService()활동을 제외한 관리 3大组件및 스케줄링 개체 생성 内存, 电池, 权限, 性能, 등 cpu의 모니터링과 같은 관련 개체 생성 ), start()시작 서비스( 移除进程组, 启动cpu线程, 등) 를 통해 일부 개체를 생성 및 초기화합니다. . 서브).注册权限电池
  4. SystemServer->run()->startBootstrapServices()->setSystemServiceManager()、setInstaller()、initPowerManagement()、setSystemProcess():
    AMS가 생성된 후 일련의 관련 초기화 및 설정이 수행됩니다.
    setSystemProcess(): Framework-res.apk의 정보를 추가하고 SystemServer进程, LoadedApk생성 , 추가 , 통일적으로 관리 합니다 SystemServer进程.ProcessRecordmPidsSelfLockedAMS
  5. SystemServer->run()->startOtherServices():
    AMS 시작 후 후속 작업으로, systemReady()메인 통화 호출 및 실행 시 전달됩니다 goingCallback.
    systemReady()/goingCallback: AMS 시작 완료 및 시스템 관련 초기화 이후 완료되는 각종 서비스나 프로세스, 기타 작업입니다. 데스크톱 응용 프로그램은 systemReady()메서드에서 시작 systemui되고 goingCallback. 데스크톱 애플리케이션이 시작되면 부팅 브로드캐스트를 보냅니다.ACTION_BOOT_COMPLETED

지금까지 전체 AMS 시작이 완료되었습니다. 다음 장에서는 Activity의 시작 과정을 설명하겠습니다.

AMS 시작 프로세스 다이어그램은 아래에 첨부되어 있습니다.
여기에 이미지 설명을 삽입하세요
여기에 이미지 설명을 삽입하세요

추천

출처blog.csdn.net/u010687761/article/details/131438970