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. 使用Asp.Net Core MVC 开发项目实践[第五篇:缓存的使用]

    项目中我们常常会碰到一些数据,需要高频率用到但是又不会频繁变动的这类,我们就可以使用缓存把这些数据缓存起来(比如说本项目的导航数据,帖子频道数据). 我们项目中常用到有Asp.Net Core 本身提 ...

  2. PHP 九九乘法表的4种表达方式

    九九乘法表的四种不同表现形式 x轴对称: //第一种 for($i=1;$i<=9;$i++){ for($j=1;$j<=$i;$j++) { echo $i.'x'.$j.'='.$i ...

  3. 使用Asp.Net Core MVC 开发项目实践[第二篇:EF Core]

    在项目中使用EF Core还是比较容易的,在这里我们使用的版本是EF Core 2.2. 1.使用nuget获取EF Core包 这个示例项目使用的是SQLSERVER,所以还需要下载Microsof ...

  4. spring cloud config与eureka配合使用

    前面两篇介绍了Spring Cloud Config服务端和客户端的简单配置,本篇介绍Spring Cloud Config与Eureka配合使用 前言 默认情况下,配置客户端启动时,都是通过配置属性 ...

  5. Strust2框架笔记01_XML配置_action编写

    目录 1.Struts2概述 1.1 什么是Struts2 1.2 Web层框架基于前端控制器模型设计 2. Struts2入门案例 2.1 Struts2的开发环境 2.2 解压开发包 2.3 创建 ...

  6. linux部分常见指令

    游走指令 cd: 进入指定位置 cd /   进入到根目录   cd /home   进入到home文件夹 cd - 进入上次所在文件夹    比如  在 / 时 cd /usr/local到loca ...

  7. blfs(systemv版本)学习笔记-配置远程访问和管理lfs系统

    我的邮箱地址:zytrenren@163.com欢迎大家交流学习纠错! 要实现远程管理和配置lfs系统需要配置以下软件包: 前几页章节脚本的配置:https://www.cnblogs.com/ren ...

  8. 【20190129】CSS-定位问题记录

    很多情况下我在写div的时候都不会把高度写死,而是用子元素撑开高度的方式,但是如果子元素设置了浮动或者position绝对定位,就相当于把子元素从文档流中拿出来了,这时父元素的高度就不能被子元素撑开了 ...

  9. 【读书笔记】iOS-基带攻击

    一,iOS设备中的蜂窝网络通信栈运行在专门的芯片上,这个芯片就是数字基带处理器. 参考资料:<黑客攻防技术宝典-iOS实战篇>

  10. lcn 分布式事务协调者集群原理

    lcn集群原理图: 1.实现原理: 1.1 LCN获取tm协调者注册地址 1. LCN客户端项目启动的时候,首先会注册到事务协调者中去,然后读取配置文件tm事务协调者的注册地址. 2. 向该事务协调者 ...