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;  

 

    其功能函数下表所示:

 

功能函数
增加删除MonitoraddMonitor(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 家族图谱

《Android Activity.startActivity流程简介》

 

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 家族图谱

《Android Activity.startActivity流程简介》

 

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 家族图谱

《Android Activity.startActivity流程简介》

 

 

6. IApplicationThread接口AMS->Application

    IApplicationThread为AMS作为客户端访问Application服务器端的Binder接口。当创建Application时,将把此Binder对象传递给AMS,然后AMS把它保存在mProcessNames.ProcessRecord.thread中。当需要通知Application工作时,则调用IApplicationThread中对应的接口函数。

   其相互关系如下图所示:

《Android Activity.startActivity流程简介》

 

    原文作者:zzfx
    原文地址: https://www.cnblogs.com/feng9exe/p/5705155.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞