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进行管理:

  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启动流程如下所示:

  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. ActivityManagerService.startActivity-> (AMS)
  16. ActivityManagerService.startActivityAsUser->
  17. ActivityStack.startActivityMayWait->
  18. ActivityStack.resolveActivity(获取ActivityInfo)
  19. //aInfo.name为main Activity,如:com.my.test.MainActivity
  20. //aInfo.applicationInfo.packageName为包名,如com.my.test
  21. ActivityStack.startActivityLocked->
  22. //ProcessRecord callerApp; 调用者即Launcher信息
  23. //ActivityRecord sourceRecord; Launcher Activity相关信息
  24. //ActivityRecord r=new ActivityRecord(...),将要创建的Activity相关信息
  25. ActivityStack.startActivityUncheckedLocked->
  26. //Activity启动方式:ActivityInfo.LAUNCH_MULTIPLE/LAUNCH_SINGLE_INSTANCE/
  27. //             ActivityInfo.LAUNCH_SINGLE_TASK/LAUNCH_SINGLE_TOP)
  28. // 创建一个新的task,即TaskRecord,并保存在ActivityRecord.task中
  29. //r.setTask(new TaskRecord(mService.mCurTask, r.info, intent), null, true)
  30. // 把新创建的Activity放在栈顶
  31. ActivityStack.startActivityLocked->
  32. ActivityStack.resumeTopActivityLocked->
  33. ActivityStack.startPausingLocked (使Launcher进入Paused状态)->
  34. /*****************************************************************
  35. * AMS通过Binder通知Launcher进入Paused状态
  36. ****************************************************************/
  37. ApplicationThreadProxy.schedulePauseActivity->
  38. //private class ApplicationThread extends ApplicationThreadNative
  39. ApplicationThread.schedulePauseActivity->
  40. ActivityThread.queueOrSendMessage->
  41. // 调用Activity.onUserLeaveHint
  42. // 调用Activity.onPause
  43. // 通知activity manager我进入了pause状态
  44. ActivityThread.handlePauseActivity->
  45. /*****************************************************************
  46. * Launcher通过Binder告诉AMS,它已经进入Paused状态
  47. ****************************************************************/
  48. ActivityManagerProxy.activityPaused->
  49. ActivityManagerService.activityPaused->
  50. ActivityStack.activityPaused->(把Activity状态修改为PAUSED)
  51. ActivityStack.completePauseLocked->
  52. // 参数为代表Launcher这个Activity的ActivityRecord
  53. // 使用栈顶的Activity进入RESUME状态
  54. ActivityStack.resumeTopActivityLokced->
  55. //topRunningActivityLocked将刚创建的放于栈顶的activity取回来
  56. // 即在ActivityStack.startActivityUncheckedLocked中创建的
  57. /*****************************************************************
  58. * AMS创建一个新的进程,用来启动一个ActivityThread实例,
  59. * 即将要启动的Activity就是在这个ActivityThread实例中运行
  60. ****************************************************************/
  61. ActivityStack.startSpecificActivityLocked->
  62. // 创建对应的ProcessRecord
  63. ActivityManagerService.startProcessLocked->
  64. // 启动一个新的进程
  65. // 新的进程会导入android.app.ActivityThread类,并且执行它的main函数,
  66. // 即实例化ActivityThread, 每个应用有且仅有一个ActivityThread实例
  67. Process.start("android.app.ActivityThread",...)->
  68. // 通过zygote机制创建一个新的进程
  69. Process.startViaZygote->
  70. // 这个函数在进程中创建一个ActivityThread实例,然后调用
  71. // 它的attach函数,接着就进入消息循环
  72. ActivityThread.main->
  73. /*****************************************************************
  74. * ActivityThread通过Binder将一个ApplicationThread类的Binder对象
  75. * 传递给AMS,以便AMS通过此Binder对象来控制Activity整个生命周期
  76. ****************************************************************/
  77. ActivityThread.attach->
  78. IActivityManager.attachApplication(mAppThread)->
  79. ActivityManagerProxy.attachApplication->
  80. ActivityManagerService.attachApplication->
  81. // 把在ActivityManagerService.startProcessLocked中创建的ProcessRecord取出来
  82. ActivityManagerService.attachApplicationLocked->
  83. /*****************************************************************
  84. * AMS通过Binder通知ActivityThread一切准备OK,它可以真正启动新的Activity了
  85. ****************************************************************/
  86. // 真正启动Activity
  87. ActivityStack.realStartActivityLocked->
  88. ApplicationThreadProxy.scheduleLaunchActivity->
  89. ApplicationThread.scheduleLaunchActivity->
  90. ActivityThread.handleLaunchActivity->
  91. // 加载新的Activity类,并执行它的onCreate
  92. ActivityThread.performLaunchActivity
  93. /*1) Instrumentation.newActivity: 加载新类,即创建Activity对象;
  94. 2) ActivityClientRecord.packageInfo.makeApplication:创建Application对象;
  95. <LoadedApk.makeApplication>
  96. 3) Activity.attach(Context context, ActivityThread aThread,
  97. Instrumentation instr, IBinder token, int ident,
  98. Application application, Intent intent, ActivityInfo info,
  99. CharSequence title, Activity parent, String id,
  100. NonConfigurationInstances lastNonConfigurationInstances,
  101. Configuration config):把Application attach到Activity, 即把Activtiy
  102. 相关信息设置到新创建的Activity中
  103. 4) Instrumentation.callActivityOnCreate:调用onCreate;*/
  104. // 使用Activity进入RESUMED状态,并调用onResume
  105. ActivityThread.handleResumeActivity

3. ActivityManagerService

3.1 类中关键信息

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

3.2 家族图谱

4. ActivityStack-真正做事的家伙

ActivityManagerService使用它来管理系统中所有的Activities的状态,Activities使用stack的方式进行管理。它是真正负责做事的家伙,很勤快的,但外界无人知道!

4.1 类中关键信息

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

4.2 家族图谱

5. ProcessRecord

记录了一个进程的相关信息。

5.1 类中关键信息

  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. IApplicationThread thread;  // the actual proc...  may be null only if
  12. // 'persistent' is true (in which case we
  13. // are in the process of launching the app)
  14. // 是ApplicationThread对象的远程接口,
  15. // 通过此接口通知Activity进入对应的状态
  16. int pid;                    // The process of this application; 0 if none
  17. ApplicationInfo instrumentationInfo; // the application being instrumented
  18. BroadcastRecord curReceiver;// receiver currently running in the app
  19. // contains HistoryRecord objects
  20. final ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
  21. // all ServiceRecord running in this process
  22. final HashSet<ServiceRecord> services = new HashSet<ServiceRecord>();
  23. // services that are currently executing code (need to remain foreground).
  24. final HashSet<ServiceRecord> executingServices
  25. = new HashSet<ServiceRecord>();
  26. // All ConnectionRecord this process holds
  27. final HashSet<ConnectionRecord> connections
  28. = new HashSet<ConnectionRecord>();
  29. // all IIntentReceivers that are registered from this process.
  30. final HashSet<ReceiverList> receivers = new HashSet<ReceiverList>();
  31. // class (String) -> ContentProviderRecord
  32. final HashMap<String, ContentProviderRecord> pubProviders
  33. = new HashMap<String, ContentProviderRecord>();
  34. // All ContentProviderRecord process is using
  35. final ArrayList<ContentProviderConnection> conProviders
  36. = new ArrayList<ContentProviderConnection>();
  37. boolean persistent;         // always keep this application running?
  38. boolean crashing;           // are we in the process of crashing?
  39. Dialog crashDialog;         // dialog being displayed due to crash.
  40. boolean notResponding;      // does the app have a not responding dialog?
  41. Dialog anrDialog;           // dialog being displayed due to app not resp.
  42. boolean removed;            // has app package been removed from device?
  43. boolean debugging;          // was app launched for debugging?
  44. boolean waitedForDebugger;  // has process show wait for debugger dialog?
  45. Dialog waitDialog;          // current wait for debugger dialog
  46. ProcessRecord(BatteryStatsImpl.Uid.Proc _batteryStats, IApplicationThread _thread,
  47. ApplicationInfo _info, String _processName, int _uid) {
  48. batteryStats = _batteryStats;
  49. info = _info;
  50. isolated = _info.uid != _uid;
  51. uid = _uid;
  52. userId = UserHandle.getUserId(_uid);
  53. processName = _processName;
  54. pkgList.add(_info.packageName);
  55. thread = _thread;
  56. maxAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
  57. hiddenAdj = clientHiddenAdj = emptyAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
  58. curRawAdj = setRawAdj = -100;
  59. curAdj = setAdj = -100;
  60. persistent = false;
  61. removed = false;
  62. }
  63. ...
  64. }

5. 2 家族图谱

6. IApplicationThread接口AMS->Application

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

其相互关系如下图所示:

Android Activity.startActivity流程简介的更多相关文章

  1. Android Activity动画属性简介

    Android Activity动画属性简介 在Android当中 设置activity的动画 需要复写 android:windowAnimationStyle这个属性 我们自定义一个动画样式来继承 ...

  2. Android Activity启动流程, app启动流程,APK打包流程, APK安装过程

    1.Activity启动流程 (7.0版本之前) 从startActivity()开始,最终都会调用startActivityForResult() 在该方法里面会调用Instrumentation. ...

  3. 【Android 系统开发】 Android 系统启动流程简介

    作者 : 万境绝尘 (octopus_truth@163.com) 转载请注明出处 : http://blog.csdn.net/shulianghan/article/details/3889548 ...

  4. Android之Activity启动流程详解(基于api28)

    前言 Activity作为Android四大组件之一,他的启动绝对没有那么简单.这里涉及到了系统服务进程,启动过程细节很多,这里我只展示主体流程.activity的启动流程随着版本的更替,代码细节一直 ...

  5. Cocos2d-x3.3RC0的Android编译Activity启动流程分析

    本文将从引擎源代码Jni分析Cocos2d-x3.3RC0的Android Activity的启动流程,以下是具体分析. 1.引擎源代码Jni.部分Java层和C++层代码分析 watermark/2 ...

  6. 浅谈Android的Activity运行流程(生命周期)

    关于Android的Activity运行流程,我们可以写一些程序来直观的查看Activity的运行流程.在这里我们使用Log工具来获取Activity运行日志.假如我们新建一个Android项目,Pr ...

  7. Android Activity 详述

    activity类处于android.app包中,继承关系: extends ContextThemeWrapper implements LayoutInflater.Factory2 Window ...

  8. Android Activity学习笔记——Activity的启动和创建

    http://www.cnblogs.com/bastard/archive/2012/04/07/2436262.html 最近学习Android相关知识,感觉仅仅了解Activity几个生命周期函 ...

  9. Android Activity启动流程源码全解析(1)

    前言 Activity是Android四大组件的老大,我们对它的生命周期方法调用顺序都烂熟于心了,可是这些生命周期方法到底是怎么调用的呢?在启动它的时候会用到startActivty这个方法,但是这个 ...

随机推荐

  1. MySQL常用的备份方式与备份工具简介

    一.MySQL备份方式与备份类型 1.备份的必要性 再生产环境中,为了防止硬件故障.软件故障.自然灾害.误操作等各种原因导致的数据库数据丢失后能恢复到事故之前的状态,我们需要对数据库进行备份和恢复操作 ...

  2. angularjs学习第五天笔记(第二篇:表单验证升级篇)

    您好,我是一名后端开发工程师,由于工作需要,现在系统的从0开始学习前端js框架之angular,每天把学习的一些心得分享出来,如果有什么说的不对的地方,请多多指正,多多包涵我这个前端菜鸟,欢迎大家的点 ...

  3. [PHP] 算法-镜像二叉树的PHP实现

    操作给定的二叉树,将其变换为源二叉树的镜像. 二叉树的镜像定义:源二叉树 8 / \ 6 10 / \ / \ 5 7 9 11 镜像二叉树 8 / \ 10 6 / \ / \ 11 9 7 5 思 ...

  4. Android开发——使用自带图标

    Android其实也是自带有许多常用的图标,我们直接使用即可 在源代码*.Java中可以进入如下方式引用: myMenuItem.setIcon(android.R.drawable.ic_menu_ ...

  5. hadoop 核心概念及入门

    Hadoop Hadoop背景 什么是HADOOP HADOOP是apache旗下的一套开源软件平台HADOOP提供利用服务器集群,根据用户的自定义业务逻辑,对海量数据进行分布式处理,HADOOP的核 ...

  6. 列表中文字太多 溢出使用省略号css方法

    我们经常会遇到文字太多,而为了不打破原有布局,需要将多出文字用省略号代替,实现以下效果: 文字太太太太多多多啦...... 这个不多. html:这是个列表.ul/ol都行. <ul> & ...

  7. 【读书笔记】iOS-WiFi长连接

    如果你的应用需要一个持久的WiFi长连接,你可以通过设置应用的Info.plist文件中的UIRequiresPersistentWiFi配置项的Boolean值来达到目的.如果这个配置项的值为YES ...

  8. 转:drupal常用api

    drupal常用api   最短的函数 // 语言字串,除了可以获取对应语言外,还可以设置字串变量.可以是!var, @var或 %var,%var就添加元素外层.@var会过滤HTML,!var会原 ...

  9. python 类函数,实例函数,静态函数

    一.实现方法 class Function(object): # 在类定义中定义变量 cls_variable = "class varibale" def __init__(se ...

  10. vue axios 与 FormData 结合 提交文件 上传文件

    ---再利用Vue.axios.FormData做上传文件时,遇到一个问题,后台虽然接收到请求,但是将文件类型识别成了字符串,所以,web端一直报500,结果是自己大意了. 1.因为使用了new  F ...