自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

談?wù)凙MS的誕生和使用

移動(dòng)開發(fā) Android
今天接著完善Android系統(tǒng)這一塊的體系架構(gòu),說(shuō)說(shuō)在App啟動(dòng)流程中舉足輕重的ActivityManagerService。

[[375159]]

前言

今天接著完善Android系統(tǒng)這一塊的體系架構(gòu),說(shuō)說(shuō)在App啟動(dòng)流程中舉足輕重的ActivityManagerService。

顧名思義,這個(gè)組件肯定是用來(lái)管理Activity的服務(wù),其實(shí)不僅是Activity,它還負(fù)責(zé)四大組件相關(guān)的啟動(dòng),切換,調(diào)度等等。

具體是怎么被啟動(dòng)的,又是怎么進(jìn)行管理的呢?一起看看吧。

(代碼基于Android9.0)

服務(wù)的啟動(dòng)

之前在SystemServer章節(jié)說(shuō)過(guò),系統(tǒng)的服務(wù)一般都是通過(guò)SystemServer進(jìn)程啟動(dòng)的,AMS也不例外。

  1. //SystemServer.java 
  2.     private void startBootstrapServices() { 
  3.         //... 
  4.  
  5.         // Activity manager runs the show. 
  6.         traceBeginAndSlog("StartActivityManager"); 
  7.         mActivityManagerService = mSystemServiceManager.startService( 
  8.                 ActivityManagerService.Lifecycle.class).getService(); 
  9.         mActivityManagerService.setSystemServiceManager(mSystemServiceManager); 
  10.         mActivityManagerService.setInstaller(installer); 
  11.         traceEnd(); 
  12.     } 
  13.  
  14.     //中間用到了反射,之前說(shuō)過(guò)。 
  15.  
  16.  
  17.     public void startService(@NonNull final SystemService service) { 
  18.         // Register it. 
  19.         mServices.add(service); 
  20.         // Start it. 
  21.         long time = SystemClock.elapsedRealtime(); 
  22.         try { 
  23.             service.onStart(); 
  24.         } catch (RuntimeException ex) { 
  25.             throw new RuntimeException("Failed to start service " + service.getClass().getName() 
  26.                     + ": onStart threw an exception", ex); 
  27.         } 
  28.     }     
  29.  
  30.  
  31. //ActivityManagerService.java 
  32.     public static final class Lifecycle extends SystemService { 
  33.         private final ActivityManagerService mService; 
  34.  
  35.         public Lifecycle(Context context) { 
  36.             super(context); 
  37.             mService = new ActivityManagerService(context); 
  38.         } 
  39.  
  40.         @Override 
  41.         public void onStart() { 
  42.             mService.start(); 
  43.         } 
  44.  
  45.         @Override 
  46.         public void onBootPhase(int phase) { 
  47.             mService.mBootPhase = phase; 
  48.             if (phase == PHASE_SYSTEM_SERVICES_READY) { 
  49.                 mService.mBatteryStatsService.systemServicesReady(); 
  50.                 mService.mServices.systemServicesReady(); 
  51.             } 
  52.         } 
  53.  
  54.         @Override 
  55.         public void onCleanupUser(int userId) { 
  56.             mService.mBatteryStatsService.onCleanupUser(userId); 
  57.         } 
  58.  
  59.         public ActivityManagerService getService() { 
  60.             return mService; 
  61.         } 
  62.     } 

可以看到,通過(guò)調(diào)用了ActivityManagerService.Lifecycle這個(gè)內(nèi)部類中的onStart方法,啟動(dòng)了AMS,并調(diào)用了AMS的start方法。

再簡(jiǎn)單看看AMS的實(shí)例化方法和start方法:

  1. public ActivityManagerService(Context systemContext) { 
  2.        mContext = systemContext; 
  3.  
  4.        mFactoryTest = FactoryTest.getMode(); 
  5.        mSystemThread = ActivityThread.currentActivityThread(); 
  6.        mUiContext = mSystemThread.getSystemUiContext(); 
  7.  
  8.  
  9.        mHandlerThread = new ServiceThread(TAG, 
  10.                THREAD_PRIORITY_FOREGROUND, false /*allowIo*/); 
  11.        mHandlerThread.start(); 
  12.        mHandler = new MainHandler(mHandlerThread.getLooper()); 
  13.        mUiHandler = mInjector.getUiHandler(this); 
  14.  
  15.        //... 
  16.  
  17.        mServices = new ActiveServices(this); 
  18.        mProviderMap = new ProviderMap(this); 
  19.        mAppErrors = new AppErrors(mUiContext, this); 
  20.  
  21.     
  22.        // TODO: Move creation of battery stats service outside of activity manager service. 
  23.        mBatteryStatsService = new BatteryStatsService(systemContext, systemDir, mHandler); 
  24.        mBatteryStatsService.getActiveStatistics().readLocked(); 
  25.        mBatteryStatsService.scheduleWriteToDisk(); 
  26.        mOnBattery = DEBUG_POWER ? true 
  27.                : mBatteryStatsService.getActiveStatistics().getIsOnBattery(); 
  28.        mBatteryStatsService.getActiveStatistics().setCallback(this); 
  29.  
  30.  
  31.        mStackSupervisor = createStackSupervisor(); 
  32.        mStackSupervisor.onConfigurationChanged(mTempConfig); 
  33.         
  34.        mActivityStartController = new ActivityStartController(this); 
  35.        mRecentTasks = createRecentTasks(); 
  36.        mStackSupervisor.setRecentTasks(mRecentTasks); 
  37.        mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mHandler); 
  38.        mLifecycleManager = new ClientLifecycleManager(); 
  39.  
  40.        mProcessCpuThread = new Thread("CpuTracker"
  41.        //... 
  42.  
  43.    } 
  44.  
  45.  
  46.    private void start() { 
  47.        removeAllProcessGroups(); 
  48.        mProcessCpuThread.start(); 
  49.  
  50.        mBatteryStatsService.publish(); 
  51.        mAppOpsService.publish(mContext); 
  52.        Slog.d("AppOps""AppOpsService published"); 
  53.        LocalServices.addService(ActivityManagerInternal.class, new LocalService()); 
  54.        // Wait for the synchronized block started in mProcessCpuThread, 
  55.        // so that any other acccess to mProcessCpuTracker from main thread 
  56.        // will be blocked during mProcessCpuTracker initialization. 
  57.        try { 
  58.            mProcessCpuInitLatch.await(); 
  59.        } catch (InterruptedException e) { 
  60.            Slog.wtf(TAG, "Interrupted wait during start", e); 
  61.            Thread.currentThread().interrupt(); 
  62.            throw new IllegalStateException("Interrupted wait during start"); 
  63.        } 
  64.    }     

代碼很長(zhǎng),我只截取了一部分。

在構(gòu)造函數(shù)中,主要初始化了一些對(duì)象,比如Context、ActivityThrad、Handler、CPU監(jiān)控線程,還有一些后文要用到的ActivityStackSupervisor、ActivityStarter等對(duì)象,

在start方法中,主要就是啟動(dòng)了CPU監(jiān)控線程,然后注冊(cè)了電池狀態(tài)服務(wù)和權(quán)限管理服務(wù)。

初始工作

AMS被啟動(dòng)之后,還會(huì)在SystemServer啟動(dòng)三大服務(wù)的時(shí)候偷偷干一些工作,我們搜索下mActivityManagerService變量就可以看到:

  1. private void startBootstrapServices() { 
  2.    //1、初始化電源管理器 
  3.       mActivityManagerService.initPowerManagement(); 
  4.       //2、為系統(tǒng)進(jìn)程設(shè)置應(yīng)用程序?qū)嵗?dòng)。 
  5.       mActivityManagerService.setSystemProcess(); 
  6.   } 
  7.  
  8.   private void startCoreServices() { 
  9.       // 啟動(dòng)UsageStatsManager,用于查詢應(yīng)用的使用情況 
  10.       mSystemServiceManager.startService(UsageStatsService.class); 
  11.       mActivityManagerService.setUsageStatsManager( 
  12.               LocalServices.getService(UsageStatsManagerInternal.class)); 
  13.       traceEnd(); 
  14.   } 
  15.  
  16.   private void startOtherServices() { 
  17.  
  18.    //安裝系統(tǒng)的Providers 
  19.       mActivityManagerService.installSystemProviders(); 
  20.  
  21.       //啟動(dòng)WMS,并為AMS設(shè)置WMS關(guān)系 
  22.       wm = WindowManagerService.main(context, inputManager, 
  23.                   mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL, 
  24.                   !mFirstBoot, mOnlyCore, new PhoneWindowManager()); 
  25.       mActivityManagerService.setWindowManager(wm); 
  26.  
  27.       //... 
  28.   } 
  29.  
  30.  
  31.  
  32.   public void setSystemProcess() { 
  33.       try { 
  34.           ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true
  35.                   DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO); 
  36.       } 
  37.   } 

其中第二步setSystemProcess方法中,會(huì)注冊(cè)AMS到ServiceManager中,這樣后續(xù)如果需要用到AMS的時(shí)候就可以通過(guò)ServiceManager進(jìn)行獲取,下面馬上就要講到。

啟動(dòng)就說(shuō)這么多,都是比較枯燥的內(nèi)容,所以也沒有深入下去,有個(gè)印象就行,以后如果需要用到相關(guān)知識(shí)就知道去哪里找了。

從啟動(dòng)流程看AMS工作內(nèi)容

為了了解AMS的具體工作,我們就從Activity的啟動(dòng)過(guò)程看起。

上文app啟動(dòng)流程中說(shuō)過(guò),startActivityForResult方法會(huì)轉(zhuǎn)到mInstrumentation.execStartActivity方法:

  1. //mInstrumentation.execStartActivity 
  2.     int result = ActivityManager.getService() 
  3.                 .startActivity(whoThread, who.getBasePackageName(), intent, 
  4.                         intent.resolveTypeIfNeeded(who.getContentResolver()), 
  5.                         token, target != null ? target.mEmbeddedID : null
  6.                         requestCode, 0, null, options); 
  7.     checkStartActivityResult(result, intent); 
  8.  
  9.  
  10.     public static IActivityManager getService() { 
  11.         return IActivityManagerSingleton.get(); 
  12.     } 
  13.  
  14.     private static final Singleton<IActivityManager> IActivityManagerSingleton = 
  15.             new Singleton<IActivityManager>() { 
  16.                 @Override 
  17.                 protected IActivityManager create() { 
  18.                     final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE); 
  19.                     final IActivityManager am = IActivityManager.Stub.asInterface(b); 
  20.                     return am; 
  21.                 } 
  22.             }; 

可以看到,最終要拿到AMS的IBinder類型引用,這里的ServiceManager.getService(Context.ACTIVITY_SERVICE)是不是有點(diǎn)熟悉,沒錯(cuò),就是剛才專門調(diào)用了setSystemProcess方法對(duì)AMS進(jìn)行了注冊(cè)在ServiceManager中。然后我們要使用相關(guān)服務(wù)的方法的時(shí)候,就通過(guò)Servermanager拿到對(duì)應(yīng)服務(wù)的引用。

這里也就是拿到了IActivityManager對(duì)象,IActivityManager其實(shí)就是AMS在當(dāng)前進(jìn)程的代理,這里的邏輯就是通過(guò)AIDL做了一個(gè)進(jìn)程間的通信。因?yàn)檫@些服務(wù),包括我們今天說(shuō)的AMS都是在SystemServer進(jìn)程中的,而我們實(shí)際用到的時(shí)候是在我們自己的應(yīng)用進(jìn)程中,所以就涉及到進(jìn)程間通信了,這里是用的Binder機(jī)制進(jìn)行通信。

Binder,ServiceManager,這是Binder通信一整套流程,不光是AMS,包括其他的WMS等服務(wù)基本上都是通過(guò)Binder機(jī)制進(jìn)行進(jìn)程間通信的,具體內(nèi)容可以期待下后面說(shuō)到的Binder章節(jié)。

接著看啟動(dòng)流程,通過(guò)Binder調(diào)用到了AMS的startActivity方法,然后會(huì)調(diào)用到ActivityStarter的startActivity方法,在這個(gè)方法中,我們發(fā)現(xiàn)一個(gè)新的類:

  1. //ActivityStarter.java 
  2. private int startActivity(...){ 
  3.         ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid, 
  4.                 callingPackage, intent, resolvedType, aInfo, mService.getGlobalConfiguration(), 
  5.                 resultRecord, resultWho, requestCode, componentSpecified, voiceSession != null
  6.                 mSupervisor, checkedOptions, sourceRecord); 
  7.         if (outActivity != null) { 
  8.             outActivity[0] = r; 
  9.         } 
  10.  
  11.         //... 
  12.  
  13.         return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags, 
  14.                 true /* doResume */, checkedOptions, inTask, outActivity);     

ActivityRecord

這個(gè)類翻譯過(guò)來(lái)是Activity的記錄,所以猜測(cè)是和Activity有關(guān),我們點(diǎn)進(jìn)去看看它里面包含了什么:

  1. final ActivityManagerService service; // owner 
  2.     final IApplicationToken.Stub appToken; // window manager token 
  3.   
  4.     final ActivityInfo info; // all about me 
  5.     ApplicationInfo appInfo; // information about activity's app 
  6.     final int userId;          // Which user is this running for
  7.     final String packageName; // the package implementing intent's component 
  8.     final String processName; // process where this component wants to run 
  9.     final String taskAffinity; // as per ActivityInfo.taskAffinity 
  10.  
  11.     private int icon;               // resource identifier of activity's icon. 
  12.     private int logo;               // resource identifier of activity's logo. 
  13.     private int theme;              // resource identifier of activity's theme. 
  14.     int launchMode;         // the launch mode activity attribute. 

我保留了一些比較常用的屬性,大家應(yīng)該都看得出來(lái)是什么了吧,比如當(dāng)前Activity的主題——theme,當(dāng)前Activity的token——apptoken,當(dāng)前Activity的包名——packageName。

所以這個(gè)ActivityRecord其實(shí)就是保存記錄了Activity的所有信息。

接著看流程,后續(xù)會(huì)執(zhí)行到startActivityUnchecked方法,這個(gè)方法中,我們又可以看到一個(gè)新的類——TaskRecord.

TaskRecord

  1. private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord, 
  2.             IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, 
  3.             int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask, 
  4.             ActivityRecord[] outActivity) { 
  5.  
  6.         if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask 
  7.                 && (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) { 
  8.             newTask = true
  9.             result = setTaskFromReuseOrCreateNewTask(taskToAffiliate, topStack); 
  10.         } else if (mSourceRecord != null) { 
  11.             result = setTaskFromSourceRecord(); 
  12.         } else if (mInTask != null) { 
  13.             result = setTaskFromInTask(); 
  14.         } else { 
  15.             // This not being started from an existing activity, and not part of a new task... 
  16.             // just put it in the top task, though these days this case should never happen. 
  17.             setTaskToCurrentTopOrCreateNewTask(); 
  18.         } 
  19.  
  20.  
  21. // 新建一個(gè)任務(wù)棧 
  22.     private void setTaskToCurrentTopOrCreateNewTask() { 
  23.         //... 
  24.         final ActivityRecord prev = mTargetStack.getTopActivity(); 
  25.         final TaskRecord task = (prev != null) ? prev.getTask() : mTargetStack.createTaskRecord( 
  26.                 mSupervisor.getNextTaskIdForUserLocked(mStartActivity.userId), mStartActivity.info, 
  27.                 mIntent, nullnulltrue, mStartActivity, mSourceRecord, mOptions); 
  28.         addOrReparentStartingActivity(task, "setTaskToCurrentTopOrCreateNewTask"); 
  29.         mTargetStack.positionChildWindowContainerAtTop(task); 
  30.     } 
  31.  
  32.     //添加Ac到棧頂 
  33.     private void addOrReparentStartingActivity(TaskRecord parent, String reason) { 
  34.         if (mStartActivity.getTask() == null || mStartActivity.getTask() == parent) { 
  35.             parent.addActivityToTop(mStartActivity); 
  36.         } else { 
  37.             mStartActivity.reparent(parent, parent.mActivities.size() /* top */, reason); 
  38.         } 
  39.     } 

從代碼中可知,當(dāng)我們啟動(dòng)的Activity需要一個(gè)新的任務(wù)棧的時(shí)候(比如啟動(dòng)模式為FLAG_ACTIVITY_NEW_TASK),我們會(huì)走到setTaskToCurrentTopOrCreateNewTask方法中,新建一個(gè)TaskRecord類,并且把當(dāng)前的Activity通過(guò)addActivityToTop方法添加到棧頂。

所以這個(gè)TaskRecord類就是一個(gè)任務(wù)棧類了,它的作用就是維護(hù)棧內(nèi)的所有Activity,進(jìn)去看看這個(gè)類有哪些變量:

  1. final int taskId;       // Unique identifier for this task. 
  2.  
  3.    /** List of all activities in the task arranged in history order */ 
  4.    final ArrayList<ActivityRecord> mActivities; 
  5.  
  6.    /** Current stack. Setter must always be used to update the value. */ 
  7.    private ActivityStack mStack; 

這里截取了一些,可以發(fā)現(xiàn)有任務(wù)id——taskId,任務(wù)棧的所有ActivityRecord——mActivities,以及這個(gè)還不知道是什么的但是我知道是用來(lái)管理所有Activity和任務(wù)棧的大管家——ActivityStack。

ActivityStack

啟動(dòng)流程再往后面走,就會(huì)走到的ActivityStackSupervisor的resumeFocusedStackTopActivityLocked方法:

  1. //ActivityStackSupervisor.java 
  2.  
  3.     /** The stack containing the launcher app. Assumed to always be attached to 
  4.      * Display.DEFAULT_DISPLAY. */ 
  5.     ActivityStack mHomeStack; 
  6.  
  7.     /** The stack currently receiving input or launching the next activity. */ 
  8.     ActivityStack mFocusedStack; 
  9.  
  10.     /** If this is the same as mFocusedStack then the activity on the top of the focused stack has 
  11.      * been resumed. If stacks are changing position this will hold the old stack until the new 
  12.      * stack becomes resumed after which it will be set to mFocusedStack. */ 
  13.     private ActivityStack mLastFocusedStack; 
  14.  
  15.  
  16.     public ActivityStackSupervisor(ActivityManagerService service, Looper looper) { 
  17.         mService = service; 
  18.         mLooper = looper; 
  19.         mHandler = new ActivityStackSupervisorHandler(looper); 
  20.     } 
  21.  
  22.  
  23.     boolean resumeFocusedStackTopActivityLocked( 
  24.             ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) { 
  25.  
  26.  
  27.         if (targetStack != null && isFocusedStack(targetStack)) { 
  28.             return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions); 
  29.         } 
  30.  
  31.         final ActivityRecord r = mFocusedStack.topRunningActivityLocked(); 
  32.         if (r == null || !r.isState(RESUMED)) { 
  33.             mFocusedStack.resumeTopActivityUncheckedLocked(nullnull); 
  34.         } else if (r.isState(RESUMED)) { 
  35.             // Kick off any lingering app transitions form the MoveTaskToFront operation. 
  36.             mFocusedStack.executeAppTransition(targetOptions); 
  37.         } 
  38.  
  39.         return false
  40.     } 

ActivityStackSupervisor是一個(gè)管理ActivityStack的類,在AMS的構(gòu)造方法中被創(chuàng)建,這個(gè)類中可以看到有一些任務(wù)棧,比如mHomeStack——包含了Launcher APP的Activity。

然后再看看ActivityStack這個(gè)大管家家里存儲(chǔ)了什么好東西:

  1. enum ActivityState { 
  2.      INITIALIZING, 
  3.      RESUMED, 
  4.      PAUSING, 
  5.      PAUSED, 
  6.      STOPPING, 
  7.      STOPPED, 
  8.      FINISHING, 
  9.      DESTROYING, 
  10.      DESTROYED 
  11.  } 
  12.  
  13.  
  14.  
  15.  private final ArrayList<TaskRecord> mTaskHistory = new ArrayList<>(); 
  16.  
  17.  final ArrayList<ActivityRecord> mLRUActivities = new ArrayList<>(); 
  18.  
  19.  ActivityRecord mPausingActivity = null
  20.  
  21.  ActivityRecord mLastPausedActivity = null;     

可以看到,在ActivityStack中:

  • 有一個(gè)枚舉ActivityState,存儲(chǔ)了Activity的所有狀態(tài)。
  • 有一些TaskRecord和ActivityRecord的列表,比如mTaskHistory——沒有被銷毀的任務(wù)棧列表,mLRUActivities——通過(guò)LRU計(jì)算的列表頭目是最近最少使用的Activity的ActivityRecord列表。
  • 還有一些特殊狀態(tài)的Activity對(duì)應(yīng)的ActivityRecord,比如正在暫停的Activity,上一個(gè)暫停過(guò)的Activity。

最后,啟動(dòng)流程會(huì)走到AMS的startProcessLocked方法,然后跟Zygote進(jìn)程通信,fork進(jìn)程。后續(xù)就不說(shuō)了。

總結(jié)

到此,AMS中重要的三個(gè)組件我們都接觸過(guò)了,分別是:

  • 管理Activity所有信息的ActivityRecord。
  • 管理一個(gè)或者多個(gè)ActivityRecord的任務(wù)棧TaskRecord.
  • 管理一個(gè)或者多個(gè)任務(wù)棧的管理者ActivityStack。

再來(lái)畫個(gè)圖總結(jié)下:

其實(shí)AMS里面的邏輯還有很多很多,不僅是Activity,還有其他三大組件的一些啟動(dòng)調(diào)度流程都是通過(guò)AMS完成的,還有Activity任務(wù)棧相關(guān)的內(nèi)容(包括taskAffinity、allowTaskReparenting),后續(xù)具體涉及到的時(shí)候會(huì)再細(xì)談。

 本文轉(zhuǎn)載自微信公眾號(hào)「碼上積木」,可以通過(guò)以下二維碼關(guān)注。轉(zhuǎn)載本文請(qǐng)聯(lián)系碼上積木公眾號(hào)。

 

責(zé)任編輯:武曉燕 來(lái)源: 碼上積木
相關(guān)推薦

2021-08-05 10:30:44

FlutterRunApp流程

2012-08-27 16:20:10

Windows 7操作系統(tǒng)

2009-10-09 14:55:02

VB.NET數(shù)組

2017-08-22 16:25:14

CSSHTML選擇器

2012-06-29 13:45:53

XML

2023-08-07 14:52:33

WindowsExplorer進(jìn)程

2016-09-09 12:51:23

PhxSQL原則局限性

2017-11-09 15:38:26

OpenRTB 3.0演化

2012-03-26 11:32:45

Java

2012-04-16 15:08:33

2016-07-01 16:13:13

AWSLambda

2024-05-20 08:21:36

Activity內(nèi)部類接口

2020-07-01 07:44:06

javaSE==equals

2018-12-26 13:22:05

NVMeNVMe-oF數(shù)據(jù)

2022-01-04 20:52:50

函數(shù)異步Promise

2015-06-29 13:54:46

WLANWi-FiWiMax

2016-12-12 13:54:37

Xcode誕生macOS

2021-10-29 16:36:53

AMSAndroidActivityMan

2021-01-21 15:36:27

AndroidAMSSDK

2017-02-21 13:24:41

iOSMVVM架構(gòu)
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)