Android Activity.startActivity流程簡介


http://blog.csdn.net/myarrow/article/details/14224273

1. 基本概念

1.1 Instrumentation是什么?

      顧名思義,儀器儀表,用於在應用程序中進行“測量”和“管理”工作。一個應用程序中只有一個Instrumentation實例對象,且每個Activity都有此對象的引用。Instrumentation將在任何應用程序運行前初始化,可以通過它監測系統與應用程序之間的所有交互,即類似於在系統與應用程序之間安裝了個“竊聽.器”。

      當ActivityThread 創建(callActivityOnCreate)、暫停、恢復某個Activity時,通過調用此對象的方法來實現,如:

         1) 創建: callActivityOnCreate 

         2) 暫停: callActivityOnPause

         3) 恢復: callActivityOnResume

     Instrumentation和ActivityThread的關系,類似於老板與經理的關系,老板負責對外交流(如與Activity Manager Service<AMS>),Instrumentation負責管理並完成老板交待的任務。

     它通過以下兩個成員變量來對當前應用進程中的Activity進行管理:

 

[java]  view plain  copy
  1. private List<ActivityWaiter> mWaitingActivities;  
  2. private List<ActivityMonitor> mActivityMonitors;  

 

    其功能函數下表所示:

 

功能 函數
增加刪除Monitor addMonitor(ActivityMonitor monitor)
removeMonitor(ActivityMonitor monitor)
Application與Activity生命周期控制 newApplication(Class<?> clazz, Context context)
newActivity(ClassLoader cl, String className,Intent intent)
callActivityOnCreate(Activity activity, Bundle icicle)
callActivityOnDestroy(Activity activity)
callActivityOnStart(Activity activity)
callActivityOnRestart(Activity activity)
callActivityOnResume(Activity activity)
callActivityOnStop(Activity activity)
callActivityOnPause(Activity activity)
Instrumentation生命周期控制 onCreate(Bundle arguments)
start()
onStart()
finish(int resultCode, Bundle results)
onDestroy()
發送用戶操控信息到當前窗口 sendCharacterSync(int keyCode)
sendPointerSync(MotionEvent event)
sendTrackballEventSync(MotionEvent event)
sendTrackballEventSync(MotionEvent event)
同步操作 startActivitySync(Intent intent) //它調用Context.startActivity
runOnMainSync(Runnable runner)
waitForIdle()

 

 

 

2. Android應用程序啟動過程(MainActivity)

 

     即MainActivity的啟動過程,在此過程中,將創建一個新的進程來執行此MainActivity。

     Android應用程序從Launcher啟動流程如下所示:

 

[java]  view plain  copy
  1. /***************************************************************** 
  2.  * Launcher通過Binder告訴ActivityManagerService, 
  3.  * 它將要啟動一個新的Activity; 
  4.  ****************************************************************/  
  5. Launcher.startActivitySafely->    
  6. Launcher.startActivity->    
  7.  //要求在新的Task中啟動此Activity    
  8.  //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)    
  9.  Activity.startActivity->    
  10.  Activity.startActivityForResult->    
  11.  Instrumentation.execStartActivity->    
  12.   // ActivityManagerNative.getDefault()返回AMS Proxy接口    
  13.   ActivityManagerNative.getDefault().startActivity->    
  14.   ActivityManagerProxy.startActivity->    
  15.     
  16.    ActivityManagerService.startActivity-> (AMS)    
  17.    ActivityManagerService.startActivityAsUser->     
  18.     
  19.     ActivityStack.startActivityMayWait->    
  20.     ActivityStack.resolveActivity(獲取ActivityInfo)    
  21.       //aInfo.name為main Activity,如:com.my.test.MainActivity    
  22.       //aInfo.applicationInfo.packageName為包名,如com.my.test    
  23.     ActivityStack.startActivityLocked->    
  24.       //ProcessRecord callerApp; 調用者即Launcher信息    
  25.       //ActivityRecord sourceRecord; Launcher Activity相關信息    
  26.       //ActivityRecord r=new ActivityRecord(...),將要創建的Activity相關信息      
  27.     ActivityStack.startActivityUncheckedLocked->    
  28.      //Activity啟動方式:ActivityInfo.LAUNCH_MULTIPLE/LAUNCH_SINGLE_INSTANCE/    
  29.      //             ActivityInfo.LAUNCH_SINGLE_TASK/LAUNCH_SINGLE_TOP)    
  30.      // 創建一個新的task,即TaskRecord,並保存在ActivityRecord.task中    
  31.      //r.setTask(new TaskRecord(mService.mCurTask, r.info, intent), null, true)    
  32.      // 把新創建的Activity放在棧頂       
  33.      ActivityStack.startActivityLocked->    
  34.      ActivityStack.resumeTopActivityLocked->    
  35.      ActivityStack.startPausingLocked (使Launcher進入Paused狀態)->      
  36.   
  37.      /***************************************************************** 
  38.       * AMS通過Binder通知Launcher進入Paused狀態 
  39.       ****************************************************************/  
  40.       ApplicationThreadProxy.schedulePauseActivity->     
  41.       //private class ApplicationThread extends ApplicationThreadNative    
  42.       ApplicationThread.schedulePauseActivity->    
  43.     
  44.        ActivityThread.queueOrSendMessage->    
  45.      
  46.        // 調用Activity.onUserLeaveHint    
  47.        // 調用Activity.onPause    
  48.        // 通知activity manager我進入了pause狀態    
  49.        ActivityThread.handlePauseActivity->    
  50.   
  51.        /***************************************************************** 
  52.         * Launcher通過Binder告訴AMS,它已經進入Paused狀態 
  53.         ****************************************************************/  
  54.        ActivityManagerProxy.activityPaused->    
  55.        ActivityManagerService.activityPaused->    
  56.        ActivityStack.activityPaused->(把Activity狀態修改為PAUSED)    
  57.        ActivityStack.completePauseLocked->    
  58.       
  59.        // 參數為代表Launcher這個Activity的ActivityRecord    
  60.        // 使用棧頂的Activity進入RESUME狀態    
  61.        ActivityStack.resumeTopActivityLokced->    
  62.          //topRunningActivityLocked將剛創建的放於棧頂的activity取回來    
  63.          // 即在ActivityStack.startActivityUncheckedLocked中創建的    
  64.   
  65.        /***************************************************************** 
  66.         * AMS創建一個新的進程,用來啟動一個ActivityThread實例, 
  67.         * 即將要啟動的Activity就是在這個ActivityThread實例中運行 
  68.         ****************************************************************/  
  69.        ActivityStack.startSpecificActivityLocked->    
  70.     
  71.         // 創建對應的ProcessRecord    
  72.         ActivityManagerService.startProcessLocked->    
  73.             
  74.          // 啟動一個新的進程    
  75.          // 新的進程會導入android.app.ActivityThread類,並且執行它的main函數,    
  76.          // 即實例化ActivityThread, 每個應用有且僅有一個ActivityThread實例    
  77.          Process.start("android.app.ActivityThread",...)->    
  78.   
  79.          // 通過zygote機制創建一個新的進程    
  80.          Process.startViaZygote->    
  81.       
  82.          // 這個函數在進程中創建一個ActivityThread實例,然后調用    
  83.          // 它的attach函數,接着就進入消息循環    
  84.          ActivityThread.main->    
  85.   
  86.          /***************************************************************** 
  87.           * ActivityThread通過Binder將一個ApplicationThread類的Binder對象 
  88.           * 傳遞給AMS,以便AMS通過此Binder對象來控制Activity整個生命周期 
  89.           ****************************************************************/  
  90.          ActivityThread.attach->    
  91.          IActivityManager.attachApplication(mAppThread)->    
  92.          ActivityManagerProxy.attachApplication->    
  93.          ActivityManagerService.attachApplication->    
  94.     
  95.          // 把在ActivityManagerService.startProcessLocked中創建的ProcessRecord取出來    
  96.          ActivityManagerService.attachApplicationLocked->    
  97.   
  98.          /***************************************************************** 
  99.           * AMS通過Binder通知ActivityThread一切准備OK,它可以真正啟動新的Activity了 
  100.           ****************************************************************/              
  101.          // 真正啟動Activity    
  102.          ActivityStack.realStartActivityLocked->    
  103.          ApplicationThreadProxy.scheduleLaunchActivity->    
  104.          ApplicationThread.scheduleLaunchActivity->    
  105.          ActivityThread.handleLaunchActivity->    
  106.            // 加載新的Activity類,並執行它的onCreate    
  107.            ActivityThread.performLaunchActivity    
  108.             /*1) Instrumentation.newActivity: 加載新類,即創建Activity對象;  
  109.               2) ActivityClientRecord.packageInfo.makeApplication:創建Application對象;  
  110.                  <LoadedApk.makeApplication>  
  111.               3) Activity.attach(Context context, ActivityThread aThread,  
  112.                     Instrumentation instr, IBinder token, int ident,  
  113.                     Application application, Intent intent, ActivityInfo info,  
  114.                     CharSequence title, Activity parent, String id,  
  115.                     NonConfigurationInstances lastNonConfigurationInstances,  
  116.                     Configuration config):把Application attach到Activity, 即把Activtiy  
  117.                                            相關信息設置到新創建的Activity中  
  118.               4) Instrumentation.callActivityOnCreate:調用onCreate;*/    
  119.       
  120.            // 使用Activity進入RESUMED狀態,並調用onResume    
  121.            ActivityThread.handleResumeActivity    



3. ActivityManagerService

3.1 類中關鍵信息

[java]  view plain  copy
  1. public final class ActivityManagerService extends ActivityManagerNative  
  2.         implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {  
  3.     ...  
  4.     // Maximum number of recent tasks that we can remember.  
  5.     static final int MAX_RECENT_TASKS = 20;  
  6.   
  7.     public ActivityStack mMainStack; // 管理Activity堆棧  
  8.   
  9.     // Whether we should show our dialogs (ANR, crash, etc) or just perform their  
  10.     // default actuion automatically.  Important for devices without direct input  
  11.     // devices.  
  12.     private boolean mShowDialogs = true;  
  13.   
  14.     /** 
  15.      * Description of a request to start a new activity, which has been held 
  16.      * due to app switches being disabled. 
  17.      */  
  18.     static class PendingActivityLaunch {  
  19.         ActivityRecord r;  
  20.         ActivityRecord sourceRecord;  
  21.         int startFlags;  
  22.     }  
  23.   
  24.   
  25.     /** 
  26.      * Activity we have told the window manager to have key focus. 
  27.      */  
  28.     ActivityRecord mFocusedActivity = null;  
  29.   
  30.     /** 
  31.      * List of intents that were used to start the most recent tasks. 
  32.      */  
  33.     final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();  
  34.   
  35.     /** 
  36.      * Process management. 
  37.      */  
  38.     final ProcessList mProcessList = new ProcessList();  
  39.   
  40.     /** 
  41.      * All of the applications we currently have running organized by name. 
  42.      * The keys are strings of the application package name (as 
  43.      * returned by the package manager), and the keys are ApplicationRecord 
  44.      * objects. 
  45.      */  
  46.     final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();  
  47.   
  48.     /** 
  49.      * The currently running isolated processes. 
  50.      */  
  51.     final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();  
  52.     ...  
  53.   
  54.     public static final Context main(int factoryTest) { //main入口函數  
  55.         AThread thr = new AThread();  
  56.         thr.start();  
  57.   
  58.         synchronized (thr) {  
  59.             while (thr.mService == null) {  
  60.                 try {  
  61.                     thr.wait();  
  62.                 } catch (InterruptedException e) {  
  63.                 }  
  64.             }  
  65.         }  
  66.   
  67.         ActivityManagerService m = thr.mService;  
  68.         mSelf = m;  
  69.         ActivityThread at = ActivityThread.systemMain();  
  70.         mSystemThread = at;  
  71.         Context context = at.getSystemContext();  
  72.         context.setTheme(android.R.style.Theme_Holo);  
  73.         m.mContext = context;  
  74.         m.mFactoryTest = factoryTest;  
  75.         m.mMainStack = new ActivityStack(m, context, true); // 創建ActivityStack  
  76.           
  77.         m.mBatteryStatsService.publish(context);  
  78.         m.mUsageStatsService.publish(context);  
  79.           
  80.         synchronized (thr) {  
  81.             thr.mReady = true;  
  82.             thr.notifyAll();  
  83.         }  
  84.   
  85.         m.startRunning(null, null, null, null);  
  86.           
  87.         return context;  
  88.     }  
  89. }  

 

3.2 家族圖譜

 

4. ActivityStack-真正做事的家伙

    ActivityManagerService使用它來管理系統中所有的Activities的狀態,Activities使用stack的方式進行管理。它是真正負責做事的家伙,很勤快的,但外界無人知道!

4.1 類中關鍵信息    

 

[java]  view plain  copy
  1. /** 
  2.  * State and management of a single stack of activities. 
  3.  */  
  4. final class ActivityStack {  
  5.     final ActivityManagerService mService;  
  6.     final boolean mMainStack;  
  7.     final Context mContext;  
  8.   
  9.     enum ActivityState {  
  10.         INITIALIZING,  
  11.         RESUMED,  
  12.         PAUSING,  
  13.         PAUSED,  
  14.         STOPPING,  
  15.         STOPPED,  
  16.         FINISHING,  
  17.         DESTROYING,  
  18.         DESTROYED  
  19.     }  
  20.   
  21.     /** 
  22.      * The back history of all previous (and possibly still 
  23.      * running) activities.  It contains HistoryRecord objects. 
  24.      */  
  25.     final ArrayList<ActivityRecord> mHistory = new ArrayList<ActivityRecord>();  
  26.   
  27.     /** 
  28.      * Used for validating app tokens with window manager. 
  29.      */  
  30.     final ArrayList<IBinder> mValidateAppTokens = new ArrayList<IBinder>();  
  31.   
  32.     /** 
  33.      * List of running activities, sorted by recent usage. 
  34.      * The first entry in the list is the least recently used. 
  35.      * It contains HistoryRecord objects. 
  36.      */  
  37.     final ArrayList<ActivityRecord> mLRUActivities = new ArrayList<ActivityRecord>();  
  38.   
  39.     /** 
  40.      * List of activities that are waiting for a new activity 
  41.      * to become visible before completing whatever operation they are 
  42.      * supposed to do. 
  43.      */  
  44.     final ArrayList<ActivityRecord> mWaitingVisibleActivities  
  45.             = new ArrayList<ActivityRecord>();  
  46.   
  47.     /** 
  48.      * List of activities that are ready to be stopped, but waiting 
  49.      * for the next activity to settle down before doing so.  It contains 
  50.      * HistoryRecord objects. 
  51.      */  
  52.     final ArrayList<ActivityRecord> mStoppingActivities  
  53.             = new ArrayList<ActivityRecord>();  
  54.   
  55.     /** 
  56.      * List of activities that are in the process of going to sleep. 
  57.      */  
  58.     final ArrayList<ActivityRecord> mGoingToSleepActivities  
  59.             = new ArrayList<ActivityRecord>();  
  60.     /** 
  61.      * When we are in the process of pausing an activity, before starting the 
  62.      * next one, this variable holds the activity that is currently being paused. 
  63.      */  
  64.     ActivityRecord mPausingActivity = null;  
  65.   
  66.     /** 
  67.      * This is the last activity that we put into the paused state.  This is 
  68.      * used to determine if we need to do an activity transition while sleeping, 
  69.      * when we normally hold the top activity paused. 
  70.      */  
  71.     ActivityRecord mLastPausedActivity = null;  
  72.   
  73.     /** 
  74.      * Current activity that is resumed, or null if there is none. 
  75.      */  
  76.     ActivityRecord mResumedActivity = null;  
  77.       
  78.     /** 
  79.      * This is the last activity that has been started.  It is only used to 
  80.      * identify when multiple activities are started at once so that the user 
  81.      * can be warned they may not be in the activity they think they are. 
  82.      */  
  83.     ActivityRecord mLastStartedActivity = null;  
  84.   
  85.     /** 
  86.      * Set to indicate whether to issue an onUserLeaving callback when a 
  87.      * newly launched activity is being brought in front of us. 
  88.      */  
  89.     boolean mUserLeaving = false;  
  90.   
  91.     ActivityStack(ActivityManagerService service, Context context, boolean mainStack) {  
  92.         mService = service;  
  93.         mContext = context;  
  94.         mMainStack = mainStack;  
  95.         ...  
  96.     }  
  97.     ...  
  98. }  

 

4.2 家族圖譜

 

5. ProcessRecord

 

      記錄了一個進程的相關信息。

5.1 類中關鍵信息

 

[java]  view plain  copy
  1. /** 
  2.  * Full information about a particular process that 
  3.  * is currently running. 
  4.  */  
  5. class ProcessRecord {  
  6.     final ApplicationInfo info; // all about the first app in the process  
  7.     final boolean isolated;     // true if this is a special isolated process  
  8.     final int uid;              // uid of process; may be different from 'info' if isolated  
  9.     final int userId;           // user of process.  
  10.     final String processName;   // name of the process  
  11.   
  12.     IApplicationThread thread;  // the actual proc...  may be null only if  
  13.                                 // 'persistent' is true (in which case we  
  14.                                 // are in the process of launching the app)  
  15.                                 // 是ApplicationThread對象的遠程接口,  
  16.                                 // 通過此接口通知Activity進入對應的狀態  
  17.                                   
  18.     int pid;                    // The process of this application; 0 if none  
  19.       
  20.   
  21.     ApplicationInfo instrumentationInfo; // the application being instrumented  
  22.   
  23.     BroadcastRecord curReceiver;// receiver currently running in the app  
  24.   
  25.     // contains HistoryRecord objects  
  26.     final ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();  
  27.   
  28.     // all ServiceRecord running in this process  
  29.     final HashSet<ServiceRecord> services = new HashSet<ServiceRecord>();  
  30.   
  31.     // services that are currently executing code (need to remain foreground).  
  32.     final HashSet<ServiceRecord> executingServices  
  33.              = new HashSet<ServiceRecord>();  
  34.   
  35.     // All ConnectionRecord this process holds  
  36.     final HashSet<ConnectionRecord> connections  
  37.             = new HashSet<ConnectionRecord>();    
  38.   
  39.     // all IIntentReceivers that are registered from this process.  
  40.     final HashSet<ReceiverList> receivers = new HashSet<ReceiverList>();  
  41.   
  42.     // class (String) -> ContentProviderRecord  
  43.     final HashMap<String, ContentProviderRecord> pubProviders  
  44.             = new HashMap<String, ContentProviderRecord>();   
  45.   
  46.     // All ContentProviderRecord process is using  
  47.     final ArrayList<ContentProviderConnection> conProviders  
  48.             = new ArrayList<ContentProviderConnection>();  
  49.       
  50.     boolean persistent;         // always keep this application running?  
  51.     boolean crashing;           // are we in the process of crashing?  
  52.     Dialog crashDialog;         // dialog being displayed due to crash.  
  53.     boolean notResponding;      // does the app have a not responding dialog?  
  54.     Dialog anrDialog;           // dialog being displayed due to app not resp.  
  55.     boolean removed;            // has app package been removed from device?  
  56.     boolean debugging;          // was app launched for debugging?  
  57.     boolean waitedForDebugger;  // has process show wait for debugger dialog?  
  58.     Dialog waitDialog;          // current wait for debugger dialog  
  59.   
  60.     ProcessRecord(BatteryStatsImpl.Uid.Proc _batteryStats, IApplicationThread _thread,  
  61.             ApplicationInfo _info, String _processName, int _uid) {  
  62.         batteryStats = _batteryStats;  
  63.         info = _info;  
  64.         isolated = _info.uid != _uid;  
  65.         uid = _uid;  
  66.         userId = UserHandle.getUserId(_uid);  
  67.         processName = _processName;  
  68.         pkgList.add(_info.packageName);  
  69.         thread = _thread;  
  70.         maxAdj = ProcessList.HIDDEN_APP_MAX_ADJ;  
  71.         hiddenAdj = clientHiddenAdj = emptyAdj = ProcessList.HIDDEN_APP_MIN_ADJ;  
  72.         curRawAdj = setRawAdj = -100;  
  73.         curAdj = setAdj = -100;  
  74.         persistent = false;  
  75.         removed = false;  
  76.     }  
  77.     ...  
  78. }  

 

5. 2 家族圖譜

 

 

6. IApplicationThread接口AMS->Application

    IApplicationThread為AMS作為客戶端訪問Application服務器端的Binder接口。當創建Application時,將把此Binder對象傳遞給AMS,然后AMS把它保存在mProcessNames.ProcessRecord.thread中。當需要通知Application工作時,則調用IApplicationThread中對應的接口函數。

   其相互關系如下圖所示:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM