AMS啟動(dòng)過程分析

AMS(ActivityManagerService)主要負(fù)責(zé)四大組件的啟動(dòng)啡氢、切換焊夸、調(diào)度以及應(yīng)用進(jìn)程的管理和調(diào)度工作幕屹。

Android系統(tǒng)啟動(dòng)流程:首先會(huì)從ROM中預(yù)定義的地方加載引導(dǎo)程序BootLoader到RAM中敬飒,并執(zhí)行BootLoader程序啟動(dòng)Linux Kernel痕鳍,然后啟動(dòng)用戶級(jí)別的第一個(gè)進(jìn)程init進(jìn)程硫豆。init進(jìn)程會(huì)解析init.rc腳本做一些初始化工作,包括掛載系統(tǒng)文件笼呆、創(chuàng)建工作目錄以及啟動(dòng)系統(tǒng)服務(wù)進(jìn)程等熊响,其中系統(tǒng)服務(wù)進(jìn)程包括Zygote、ServiceManager诗赌、Media等汗茄。在Zygote中會(huì)進(jìn)一步啟動(dòng)system_server進(jìn)程,然后system_server進(jìn)程中會(huì)啟動(dòng)AMS铭若、WMS洪碳、PMS等服務(wù),這些服務(wù)啟動(dòng)后叼屠,AMS就會(huì)打開Launcher應(yīng)用的home Activity瞳腌,最終就看到了手機(jī)桌面。

AMS是在SystemServer中被添加的

//SystemServer.java
/**
 * The main entry point from zygote.
 */
public static void main(String[] args) {
  //new SystemServer()中創(chuàng)建了ActivityThread
  new SystemServer().run();
}

private void run() {
  //創(chuàng)建主線程Looper
  Looper.prepareMainLooper();
  //創(chuàng)建系統(tǒng)context(new ContextImpl)和加載系統(tǒng)資源
  createSystemContext();
  //啟動(dòng)引導(dǎo)服務(wù)
  startBootstrapServices();
  //啟動(dòng)核心服務(wù)
  startCoreServices();
  //啟動(dòng)其它服務(wù)
  startOtherServices();
  //loop循環(huán)
  Looper.loop();
}

SystemServer類的main中初始化SystemServer對(duì)象镜雨,調(diào)用run方法:

1)createSystemContext:創(chuàng)建系統(tǒng)上下文
2)startBootstrapServices:啟動(dòng)引導(dǎo)服務(wù)
3)startCoreServices:啟動(dòng)核心服務(wù)
4)startOtherServices:啟動(dòng)其它服務(wù)
5)Looper.loop:loop循環(huán)

startBootstrapServices中啟動(dòng)了AMS

private void startBootstrapServices() {
  //啟動(dòng)AMS
  mActivityManagerService = ActivityManagerService.Lifecycle.startService(
                        mSystemServiceManager, atm);
  mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
  mActivityManagerService.setInstaller(installer);
  
  //③將AMS注冊(cè)到ServiceManager中
  mActivityManagerService.setSystemProcess();
}
public static final class Lifecycle extends SystemService {
  private final ActivityManagerService mService;
  private static ActivityTaskManagerService sAtm;

  //ActivityManagerService.Lifecycle這個(gè)類的構(gòu)造方法
  public Lifecycle(Context context) {
    super(context);
    //①創(chuàng)建AMS實(shí)例
    mService = new ActivityManagerService(context, sAtm);
  }
 
  public static ActivityManagerService startService(
    SystemServiceManager ssm, ActivityTaskManagerService atm) {
    sAtm = atm;
    //通過LifeCycle的getService返回AMS對(duì)象
    return ssm.startService(ActivityManagerService.Lifecycle.class).getService();
  }
  
  @Override
  public void onStart() {
    //②啟動(dòng)AMS
    mService.start();
  }
  
  public ActivityManagerService getService() {
    return mService;
  }
}
public <T extends SystemService> T startService(Class<T> serviceClass) {
  //通過反射創(chuàng)建AMS對(duì)象嫂侍,會(huì)調(diào)到上面ActivityManagerService.Lifecycle構(gòu)造方法
  Constructor<T> constructor = serviceClass.getConstructor(Context.class);
  service = constructor.newInstance(mContext);
  startService(service);
  return service;
}
// Services that should receive lifecycle events.
private final ArrayList<SystemService> mServices = new ArrayList<SystemService>();

public void startService(@NonNull final SystemService service) {
  // Register it.
  mServices.add(service);
  //開啟服務(wù)
  service.onStart();
}

①創(chuàng)建AMS實(shí)例:new ActivityManagerService

public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
  mInjector = new Injector();
  //獲取系統(tǒng)上下文環(huán)境
  mContext = systemContext;
  //獲取當(dāng)前ActivityThread線程
  mSystemThread = ActivityThread.currentActivityThread();
  //賦值mUiContext
  mUiContext = mSystemThread.getSystemUiContext();
  
  //創(chuàng)建Handler線程,用來處理handler消息
  mHandlerThread = new ServiceThread(TAG,
                THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
  mHandlerThread.start();
  mHandler = new MainHandler(mHandlerThread.getLooper());
  //處理ui相關(guān)msg的Handler
  mUiHandler = mInjector.getUiHandler(this);
  
  //初始化前臺(tái)廣播的隊(duì)列荚坞,設(shè)置10s超時(shí)
  mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
                "foreground", foreConstants, false);
  //初始化后臺(tái)廣播的隊(duì)列挑宠,設(shè)置60s超時(shí)
  mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
                "background", backConstants, true);
  //初始化離線廣播的隊(duì)列,設(shè)置60s超時(shí)
  mOffloadBroadcastQueue = new BroadcastQueue(this, mHandler,
                 "offload", offloadConstants, true);
  mBroadcastQueues[0] = mFgBroadcastQueue;
  mBroadcastQueues[1] = mBgBroadcastQueue;
  mBroadcastQueues[2] = mOffloadBroadcastQueue;
  
  //初始化管理Service的ActiveServices對(duì)象
  mServices = new ActiveServices(this);
  mProviderMap = new ProviderMap(this);
  mPackageWatchdog = PackageWatchdog.getInstance(mUiContext);
  mAppErrors = new AppErrors(mUiContext, this, mPackageWatchdog);
  //創(chuàng)建電池狀態(tài)服務(wù)
   mBatteryStatsService = new BatteryStatsService(systemContext, systemDir,
                BackgroundThread.get().getHandler());
  mBatteryStatsService.getActiveStatistics().readLocked();
  mBatteryStatsService.scheduleWriteToDisk();
  mOnBattery = DEBUG_POWER ? true
    : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
  mBatteryStatsService.getActiveStatistics().setCallback(this);
  mOomAdjProfiler.batteryPowerChanged(mOnBattery);
  
  //啟動(dòng)一個(gè)線程跟進(jìn)CPU當(dāng)前狀態(tài)信息
  mProcessCpuThread = new Thread("CpuTracker"){
    @Override
    public void run() {
      synchronized (mProcessCpuTracker) {
        mProcessCpuInitLatch.countDown();
        mProcessCpuTracker.init();
      }
      while (true) {
        try {
          try {
            synchronized(this) {
              final long now = SystemClock.uptimeMillis();
              long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
              long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
              //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
              //        + ", write delay=" + nextWriteDelay);
              if (nextWriteDelay < nextCpuDelay) {
                nextCpuDelay = nextWriteDelay;
              }
              if (nextCpuDelay > 0) {
                mProcessCpuMutexFree.set(true);
                this.wait(nextCpuDelay);
              }
            }
          } catch (InterruptedException e) {
          }
          updateCpuStatsNow();
        } catch (Exception e) {
          Slog.e(TAG, "Unexpected exception collecting process stats", e);
        }
      }
    }
  }
  //看門狗西剥,監(jiān)聽進(jìn)程
  Watchdog.getInstance().addMonitor(this);
  Watchdog.getInstance().addThread(mHandler);
}

②啟動(dòng)AMS

private void start() {
  //移除所有的進(jìn)程組
    removeAllProcessGroups();
  //啟動(dòng)Cpu進(jìn)程
  mProcessCpuThread.start();
  //啟動(dòng)電池狀態(tài)服務(wù)
  mBatteryStatsService.publish();
  mAppOpsService.publish(mContext);
  //創(chuàng)建本地服務(wù)并注冊(cè)痹栖,將創(chuàng)建的本地服務(wù)放入本地服務(wù)集合完成注冊(cè)
  LocalServices.addService(ActivityManagerInternal.class, new LocalService());
  
  //等待mProcessCpuThread完成初始化后亿汞,釋放鎖
  try {
    mProcessCpuInitLatch.await();
  } catch (InterruptedException e) {
    Slog.wtf(TAG, "Interrupted wait during start", e);
    Thread.currentThread().interrupt();
    throw new IllegalStateException("Interrupted wait during start");
  }
}

1)removeAllProcessGroups:移除所有的進(jìn)程組
2)mProcessCpuThread.start():啟動(dòng)CpuTracker線程
3)mBatteryStatsService.publish():啟動(dòng)電池狀態(tài)服務(wù)
4)LocalServices.addService(ActivityManagerInternal.class, new LocalService()):創(chuàng)建本地服務(wù)并放入本地服務(wù)集合

③將AMS注冊(cè)到ServiceManager中 setSystemProcess

public void setSystemProcess() {
  try {
        //將AMS注冊(cè)到ServiceManager中
    ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
                              DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
    //注冊(cè)進(jìn)程狀態(tài)服務(wù)
    ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
    //注冊(cè)內(nèi)存Binder
    ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false,
                              DUMP_FLAG_PRIORITY_HIGH);
    //注冊(cè)圖像信息Binder
    ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
    //注冊(cè)數(shù)據(jù)庫Binder 
    ServiceManager.addService("dbinfo", new DbBinder(this));
    if (MONITOR_CPU_USAGE) {
      //注冊(cè)監(jiān)控CPU使用狀態(tài)Binder
      ServiceManager.addService("cpuinfo", new CpuBinder(this),
                                /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
    }
    //注冊(cè)權(quán)限控制Binder
    ServiceManager.addService("permission", new PermissionController(this));
    //注冊(cè)進(jìn)程服務(wù)Binder
    ServiceManager.addService("processinfo", new ProcessInfoService(this));
        //查詢并處理ApplicationInfo
    ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
      "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
    //將Application信息配置到ActivityThread中
    mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());

    synchronized (this) {
      //創(chuàng)建并處理ProcessRecord
      ProcessRecord app = mProcessList.newProcessRecordLocked(info, info.processName,
                                                              false,
                                                              0,
                                                              new HostingRecord("system"));
      app.setPersistent(true);
      app.pid = MY_PID;
      app.getWindowProcessController().setPid(MY_PID);
      app.maxAdj = ProcessList.SYSTEM_ADJ;
      app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
      mPidsSelfLocked.put(app);
      mProcessList.updateLruProcessLocked(app, false, null);
      updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
    }
  } catch (PackageManager.NameNotFoundException e) {
    throw new RuntimeException(
      "Unable to find android system package", e);
  }

  // Start watching app ops after we and the package manager are up and running.
  mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null,
          new IAppOpsCallback.Stub() {
              @Override public void opChanged(int op, int uid, String packageName) {
                   if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && packageName != null) {
                       if (mAppOpsService.checkOperation(op, uid, packageName)
                             != AppOpsManager.MODE_ALLOWED) {
                         runInBackgroundDisabled(uid);
                       }
                   }
              }
          });
}

1)添加了各種服務(wù)瞭空,如AMS
2)mSystemThread.installSystemApplicationInfo:最終調(diào)到LoadedApk,這是應(yīng)用的基本信息

接著看startOtherServices

private void startOtherServices() {
  //AMS與WMS關(guān)聯(lián)
  mActivityManagerService.setWindowManager(wm);
  //安裝ContentProvider
  mActivityManagerService.installSystemProviders();
  //所有的服務(wù)已經(jīng)準(zhǔn)備就緒
  mActivityManagerService.systemReady(() -> {
    //啟動(dòng)系統(tǒng)UI
    startSystemUi(context, windowManagerF);
    //執(zhí)行一系列服務(wù)的systemReady
    networkStatsF.systemReady();
    //...
  }
}

installSystemProviders

public final void installSystemProviders() {
    List<ProviderInfo> providers;
    synchronized (this) {
        //找到名為"system"的進(jìn)程,就是setSystemProcess中創(chuàng)建的ProcessRecord對(duì)象
        ProcessRecord app = mProcessList.mProcessNames.get("system", SYSTEM_UID);
        providers = generateApplicationProvidersLocked(app);
        if (providers != null) {
            for (int i=providers.size()-1; i>=0; i--) {
                ProviderInfo pi = (ProviderInfo)providers.get(i);
                if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
                    //移除非系統(tǒng)provider
                    Slog.w(TAG, "Not installing system proc provider " + pi.name
                            + ": not system .apk");
                    providers.remove(i);
                }
            }
        }
    }
    if (providers != null) {
        //安全所有的系統(tǒng)provider
        mSystemThread.installSystemProviders(providers);
    }

    synchronized (this) {
        mSystemProvidersInstalled = true;
    }
    mConstants.start(mContext.getContentResolver());
    //創(chuàng)建核心Settings Observer咆畏,用于監(jiān)聽Settings的改變
    mCoreSettingsObserver = new CoreSettingsObserver(this);
    mActivityTaskManager.installSystemProviders();
    //開發(fā)者權(quán)限
    mDevelopmentSettingsObserver = new DevelopmentSettingsObserver();
    SettingsToPropertiesMapper.start(mContext.getContentResolver());
    mOomAdjuster.initSettings();

    // Now that the settings provider is published we can consider sending
    // in a rescue party.
    RescueParty.onSettingsProviderPublished(mContext);

    //mUsageStatsService.monitorPackages();
}

1)installSystemProviders:安裝系統(tǒng)Provider
2)new CoreSettingsObserver(this):創(chuàng)建CoreSettingsObserver南捂,用于監(jiān)聽系統(tǒng)設(shè)置的改變

systemReady

public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
  //啟動(dòng)Launcher界面
  mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");
}

小結(jié):

1、new SystemServer()創(chuàng)建了ActivityThread
2旧找、SystemServer的run方法中:
1)通過createSystemContext方法創(chuàng)建系統(tǒng)上下文對(duì)象
2)在startBootstrapServices方法中調(diào)用構(gòu)造方法對(duì)AMS進(jìn)行初始化溺健,start方法啟動(dòng)AMS
3)調(diào)用setSystemProcess將AMS注冊(cè)到ServiceManager中
4)在startOtherServices中安裝了系統(tǒng)Provider
5)調(diào)用systemReady啟動(dòng)Launcher界面

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市钮蛛,隨后出現(xiàn)的幾起案子鞭缭,更是在濱河造成了極大的恐慌,老刑警劉巖魏颓,帶你破解...
    沈念sama閱讀 206,126評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件岭辣,死亡現(xiàn)場離奇詭異,居然都是意外死亡甸饱,警方通過查閱死者的電腦和手機(jī)沦童,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,254評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來叹话,“玉大人偷遗,你說我怎么就攤上這事⊥蘸” “怎么了氏豌?”我有些...
    開封第一講書人閱讀 152,445評(píng)論 0 341
  • 文/不壞的土叔 我叫張陵,是天一觀的道長辅柴。 經(jīng)常有香客問我箩溃,道長,這世上最難降的妖魔是什么碌嘀? 我笑而不...
    開封第一講書人閱讀 55,185評(píng)論 1 278
  • 正文 為了忘掉前任涣旨,我火速辦了婚禮,結(jié)果婚禮上股冗,老公的妹妹穿的比我還像新娘霹陡。我一直安慰自己,他們只是感情好止状,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,178評(píng)論 5 371
  • 文/花漫 我一把揭開白布烹棉。 她就那樣靜靜地躺著,像睡著了一般怯疤。 火紅的嫁衣襯著肌膚如雪浆洗。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 48,970評(píng)論 1 284
  • 那天集峦,我揣著相機(jī)與錄音伏社,去河邊找鬼抠刺。 笑死,一個(gè)胖子當(dāng)著我的面吹牛摘昌,可吹牛的內(nèi)容都是我干的速妖。 我是一名探鬼主播,決...
    沈念sama閱讀 38,276評(píng)論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼聪黎,長吁一口氣:“原來是場噩夢啊……” “哼罕容!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起稿饰,我...
    開封第一講書人閱讀 36,927評(píng)論 0 259
  • 序言:老撾萬榮一對(duì)情侶失蹤锦秒,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后喉镰,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體脂崔,經(jīng)...
    沈念sama閱讀 43,400評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,883評(píng)論 2 323
  • 正文 我和宋清朗相戀三年梧喷,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了砌左。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 37,997評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡铺敌,死狀恐怖汇歹,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情偿凭,我是刑警寧澤产弹,帶...
    沈念sama閱讀 33,646評(píng)論 4 322
  • 正文 年R本政府宣布,位于F島的核電站弯囊,受9級(jí)特大地震影響痰哨,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜匾嘱,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,213評(píng)論 3 307
  • 文/蒙蒙 一斤斧、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧霎烙,春花似錦撬讽、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,204評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至尝蠕,卻和暖如春烘豌,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背看彼。 一陣腳步聲響...
    開封第一講書人閱讀 31,423評(píng)論 1 260
  • 我被黑心中介騙來泰國打工廊佩, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留昧捷,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 45,423評(píng)論 2 352
  • 正文 我出身青樓罐寨,卻偏偏與公主長得像,于是被迫代替她去往敵國和親鸯绿。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,722評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容