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进行管理:
- private List<ActivityWaiter> mWaitingActivities;
- 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启动流程如下所示:
- /*****************************************************************
- * Launcher通过Binder告诉ActivityManagerService,
- * 它将要启动一个新的Activity;
- ****************************************************************/
- Launcher.startActivitySafely->
- Launcher.startActivity->
- //要求在新的Task中启动此Activity
- //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
- Activity.startActivity->
- Activity.startActivityForResult->
- Instrumentation.execStartActivity->
- // ActivityManagerNative.getDefault()返回AMS Proxy接口
- ActivityManagerNative.getDefault().startActivity->
- ActivityManagerProxy.startActivity->
- ActivityManagerService.startActivity-> (AMS)
- ActivityManagerService.startActivityAsUser->
- ActivityStack.startActivityMayWait->
- ActivityStack.resolveActivity(获取ActivityInfo)
- //aInfo.name为main Activity,如:com.my.test.MainActivity
- //aInfo.applicationInfo.packageName为包名,如com.my.test
- ActivityStack.startActivityLocked->
- //ProcessRecord callerApp; 调用者即Launcher信息
- //ActivityRecord sourceRecord; Launcher Activity相关信息
- //ActivityRecord r=new ActivityRecord(...),将要创建的Activity相关信息
- ActivityStack.startActivityUncheckedLocked->
- //Activity启动方式:ActivityInfo.LAUNCH_MULTIPLE/LAUNCH_SINGLE_INSTANCE/
- // ActivityInfo.LAUNCH_SINGLE_TASK/LAUNCH_SINGLE_TOP)
- // 创建一个新的task,即TaskRecord,并保存在ActivityRecord.task中
- //r.setTask(new TaskRecord(mService.mCurTask, r.info, intent), null, true)
- // 把新创建的Activity放在栈顶
- ActivityStack.startActivityLocked->
- ActivityStack.resumeTopActivityLocked->
- ActivityStack.startPausingLocked (使Launcher进入Paused状态)->
- /*****************************************************************
- * AMS通过Binder通知Launcher进入Paused状态
- ****************************************************************/
- ApplicationThreadProxy.schedulePauseActivity->
- //private class ApplicationThread extends ApplicationThreadNative
- ApplicationThread.schedulePauseActivity->
- ActivityThread.queueOrSendMessage->
- // 调用Activity.onUserLeaveHint
- // 调用Activity.onPause
- // 通知activity manager我进入了pause状态
- ActivityThread.handlePauseActivity->
- /*****************************************************************
- * Launcher通过Binder告诉AMS,它已经进入Paused状态
- ****************************************************************/
- ActivityManagerProxy.activityPaused->
- ActivityManagerService.activityPaused->
- ActivityStack.activityPaused->(把Activity状态修改为PAUSED)
- ActivityStack.completePauseLocked->
- // 参数为代表Launcher这个Activity的ActivityRecord
- // 使用栈顶的Activity进入RESUME状态
- ActivityStack.resumeTopActivityLokced->
- //topRunningActivityLocked将刚创建的放于栈顶的activity取回来
- // 即在ActivityStack.startActivityUncheckedLocked中创建的
- /*****************************************************************
- * AMS创建一个新的进程,用来启动一个ActivityThread实例,
- * 即将要启动的Activity就是在这个ActivityThread实例中运行
- ****************************************************************/
- ActivityStack.startSpecificActivityLocked->
- // 创建对应的ProcessRecord
- ActivityManagerService.startProcessLocked->
- // 启动一个新的进程
- // 新的进程会导入android.app.ActivityThread类,并且执行它的main函数,
- // 即实例化ActivityThread, 每个应用有且仅有一个ActivityThread实例
- Process.start("android.app.ActivityThread",...)->
- // 通过zygote机制创建一个新的进程
- Process.startViaZygote->
- // 这个函数在进程中创建一个ActivityThread实例,然后调用
- // 它的attach函数,接着就进入消息循环
- ActivityThread.main->
- /*****************************************************************
- * ActivityThread通过Binder将一个ApplicationThread类的Binder对象
- * 传递给AMS,以便AMS通过此Binder对象来控制Activity整个生命周期
- ****************************************************************/
- ActivityThread.attach->
- IActivityManager.attachApplication(mAppThread)->
- ActivityManagerProxy.attachApplication->
- ActivityManagerService.attachApplication->
- // 把在ActivityManagerService.startProcessLocked中创建的ProcessRecord取出来
- ActivityManagerService.attachApplicationLocked->
- /*****************************************************************
- * AMS通过Binder通知ActivityThread一切准备OK,它可以真正启动新的Activity了
- ****************************************************************/
- // 真正启动Activity
- ActivityStack.realStartActivityLocked->
- ApplicationThreadProxy.scheduleLaunchActivity->
- ApplicationThread.scheduleLaunchActivity->
- ActivityThread.handleLaunchActivity->
- // 加载新的Activity类,并执行它的onCreate
- ActivityThread.performLaunchActivity
- /*1) Instrumentation.newActivity: 加载新类,即创建Activity对象;
- 2) ActivityClientRecord.packageInfo.makeApplication:创建Application对象;
- <LoadedApk.makeApplication>
- 3) Activity.attach(Context context, ActivityThread aThread,
- Instrumentation instr, IBinder token, int ident,
- Application application, Intent intent, ActivityInfo info,
- CharSequence title, Activity parent, String id,
- NonConfigurationInstances lastNonConfigurationInstances,
- Configuration config):把Application attach到Activity, 即把Activtiy
- 相关信息设置到新创建的Activity中
- 4) Instrumentation.callActivityOnCreate:调用onCreate;*/
- // 使用Activity进入RESUMED状态,并调用onResume
- ActivityThread.handleResumeActivity
3. ActivityManagerService
3.1 类中关键信息
- public final class ActivityManagerService extends ActivityManagerNative
- implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
- ...
- // Maximum number of recent tasks that we can remember.
- static final int MAX_RECENT_TASKS = 20;
- public ActivityStack mMainStack; // 管理Activity堆栈
- // Whether we should show our dialogs (ANR, crash, etc) or just perform their
- // default actuion automatically. Important for devices without direct input
- // devices.
- private boolean mShowDialogs = true;
- /**
- * Description of a request to start a new activity, which has been held
- * due to app switches being disabled.
- */
- static class PendingActivityLaunch {
- ActivityRecord r;
- ActivityRecord sourceRecord;
- int startFlags;
- }
- /**
- * Activity we have told the window manager to have key focus.
- */
- ActivityRecord mFocusedActivity = null;
- /**
- * List of intents that were used to start the most recent tasks.
- */
- final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
- /**
- * Process management.
- */
- final ProcessList mProcessList = new ProcessList();
- /**
- * All of the applications we currently have running organized by name.
- * The keys are strings of the application package name (as
- * returned by the package manager), and the keys are ApplicationRecord
- * objects.
- */
- final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
- /**
- * The currently running isolated processes.
- */
- final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
- ...
- public static final Context main(int factoryTest) { //main入口函数
- AThread thr = new AThread();
- thr.start();
- synchronized (thr) {
- while (thr.mService == null) {
- try {
- thr.wait();
- } catch (InterruptedException e) {
- }
- }
- }
- ActivityManagerService m = thr.mService;
- mSelf = m;
- ActivityThread at = ActivityThread.systemMain();
- mSystemThread = at;
- Context context = at.getSystemContext();
- context.setTheme(android.R.style.Theme_Holo);
- m.mContext = context;
- m.mFactoryTest = factoryTest;
- m.mMainStack = new ActivityStack(m, context, true); // 创建ActivityStack
- m.mBatteryStatsService.publish(context);
- m.mUsageStatsService.publish(context);
- synchronized (thr) {
- thr.mReady = true;
- thr.notifyAll();
- }
- m.startRunning(null, null, null, null);
- return context;
- }
- }
3.2 家族图谱
4. ActivityStack-真正做事的家伙
ActivityManagerService使用它来管理系统中所有的Activities的状态,Activities使用stack的方式进行管理。它是真正负责做事的家伙,很勤快的,但外界无人知道!
4.1 类中关键信息
- /**
- * State and management of a single stack of activities.
- */
- final class ActivityStack {
- final ActivityManagerService mService;
- final boolean mMainStack;
- final Context mContext;
- enum ActivityState {
- INITIALIZING,
- RESUMED,
- PAUSING,
- PAUSED,
- STOPPING,
- STOPPED,
- FINISHING,
- DESTROYING,
- DESTROYED
- }
- /**
- * The back history of all previous (and possibly still
- * running) activities. It contains HistoryRecord objects.
- */
- final ArrayList<ActivityRecord> mHistory = new ArrayList<ActivityRecord>();
- /**
- * Used for validating app tokens with window manager.
- */
- final ArrayList<IBinder> mValidateAppTokens = new ArrayList<IBinder>();
- /**
- * List of running activities, sorted by recent usage.
- * The first entry in the list is the least recently used.
- * It contains HistoryRecord objects.
- */
- final ArrayList<ActivityRecord> mLRUActivities = new ArrayList<ActivityRecord>();
- /**
- * List of activities that are waiting for a new activity
- * to become visible before completing whatever operation they are
- * supposed to do.
- */
- final ArrayList<ActivityRecord> mWaitingVisibleActivities
- = new ArrayList<ActivityRecord>();
- /**
- * List of activities that are ready to be stopped, but waiting
- * for the next activity to settle down before doing so. It contains
- * HistoryRecord objects.
- */
- final ArrayList<ActivityRecord> mStoppingActivities
- = new ArrayList<ActivityRecord>();
- /**
- * List of activities that are in the process of going to sleep.
- */
- final ArrayList<ActivityRecord> mGoingToSleepActivities
- = new ArrayList<ActivityRecord>();
- /**
- * When we are in the process of pausing an activity, before starting the
- * next one, this variable holds the activity that is currently being paused.
- */
- ActivityRecord mPausingActivity = null;
- /**
- * This is the last activity that we put into the paused state. This is
- * used to determine if we need to do an activity transition while sleeping,
- * when we normally hold the top activity paused.
- */
- ActivityRecord mLastPausedActivity = null;
- /**
- * Current activity that is resumed, or null if there is none.
- */
- ActivityRecord mResumedActivity = null;
- /**
- * This is the last activity that has been started. It is only used to
- * identify when multiple activities are started at once so that the user
- * can be warned they may not be in the activity they think they are.
- */
- ActivityRecord mLastStartedActivity = null;
- /**
- * Set to indicate whether to issue an onUserLeaving callback when a
- * newly launched activity is being brought in front of us.
- */
- boolean mUserLeaving = false;
- ActivityStack(ActivityManagerService service, Context context, boolean mainStack) {
- mService = service;
- mContext = context;
- mMainStack = mainStack;
- ...
- }
- ...
- }
4.2 家族图谱
5. ProcessRecord
记录了一个进程的相关信息。
5.1 类中关键信息
- /**
- * Full information about a particular process that
- * is currently running.
- */
- class ProcessRecord {
- final ApplicationInfo info; // all about the first app in the process
- final boolean isolated; // true if this is a special isolated process
- final int uid; // uid of process; may be different from 'info' if isolated
- final int userId; // user of process.
- final String processName; // name of the process
- IApplicationThread thread; // the actual proc... may be null only if
- // 'persistent' is true (in which case we
- // are in the process of launching the app)
- // 是ApplicationThread对象的远程接口,
- // 通过此接口通知Activity进入对应的状态
- int pid; // The process of this application; 0 if none
- ApplicationInfo instrumentationInfo; // the application being instrumented
- BroadcastRecord curReceiver;// receiver currently running in the app
- // contains HistoryRecord objects
- final ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
- // all ServiceRecord running in this process
- final HashSet<ServiceRecord> services = new HashSet<ServiceRecord>();
- // services that are currently executing code (need to remain foreground).
- final HashSet<ServiceRecord> executingServices
- = new HashSet<ServiceRecord>();
- // All ConnectionRecord this process holds
- final HashSet<ConnectionRecord> connections
- = new HashSet<ConnectionRecord>();
- // all IIntentReceivers that are registered from this process.
- final HashSet<ReceiverList> receivers = new HashSet<ReceiverList>();
- // class (String) -> ContentProviderRecord
- final HashMap<String, ContentProviderRecord> pubProviders
- = new HashMap<String, ContentProviderRecord>();
- // All ContentProviderRecord process is using
- final ArrayList<ContentProviderConnection> conProviders
- = new ArrayList<ContentProviderConnection>();
- boolean persistent; // always keep this application running?
- boolean crashing; // are we in the process of crashing?
- Dialog crashDialog; // dialog being displayed due to crash.
- boolean notResponding; // does the app have a not responding dialog?
- Dialog anrDialog; // dialog being displayed due to app not resp.
- boolean removed; // has app package been removed from device?
- boolean debugging; // was app launched for debugging?
- boolean waitedForDebugger; // has process show wait for debugger dialog?
- Dialog waitDialog; // current wait for debugger dialog
- ProcessRecord(BatteryStatsImpl.Uid.Proc _batteryStats, IApplicationThread _thread,
- ApplicationInfo _info, String _processName, int _uid) {
- batteryStats = _batteryStats;
- info = _info;
- isolated = _info.uid != _uid;
- uid = _uid;
- userId = UserHandle.getUserId(_uid);
- processName = _processName;
- pkgList.add(_info.packageName);
- thread = _thread;
- maxAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
- hiddenAdj = clientHiddenAdj = emptyAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
- curRawAdj = setRawAdj = -100;
- curAdj = setAdj = -100;
- persistent = false;
- removed = false;
- }
- ...
- }
5. 2 家族图谱
6. IApplicationThread接口AMS->Application
IApplicationThread为AMS作为客户端访问Application服务器端的Binder接口。当创建Application时,将把此Binder对象传递给AMS,然后AMS把它保存在mProcessNames.ProcessRecord.thread中。当需要通知Application工作时,则调用IApplicationThread中对应的接口函数。
其相互关系如下图所示:
Android Activity.startActivity流程简介的更多相关文章
- Android Activity动画属性简介
Android Activity动画属性简介 在Android当中 设置activity的动画 需要复写 android:windowAnimationStyle这个属性 我们自定义一个动画样式来继承 ...
- Android Activity启动流程, app启动流程,APK打包流程, APK安装过程
1.Activity启动流程 (7.0版本之前) 从startActivity()开始,最终都会调用startActivityForResult() 在该方法里面会调用Instrumentation. ...
- 【Android 系统开发】 Android 系统启动流程简介
作者 : 万境绝尘 (octopus_truth@163.com) 转载请注明出处 : http://blog.csdn.net/shulianghan/article/details/3889548 ...
- Android之Activity启动流程详解(基于api28)
前言 Activity作为Android四大组件之一,他的启动绝对没有那么简单.这里涉及到了系统服务进程,启动过程细节很多,这里我只展示主体流程.activity的启动流程随着版本的更替,代码细节一直 ...
- Cocos2d-x3.3RC0的Android编译Activity启动流程分析
本文将从引擎源代码Jni分析Cocos2d-x3.3RC0的Android Activity的启动流程,以下是具体分析. 1.引擎源代码Jni.部分Java层和C++层代码分析 watermark/2 ...
- 浅谈Android的Activity运行流程(生命周期)
关于Android的Activity运行流程,我们可以写一些程序来直观的查看Activity的运行流程.在这里我们使用Log工具来获取Activity运行日志.假如我们新建一个Android项目,Pr ...
- Android Activity 详述
activity类处于android.app包中,继承关系: extends ContextThemeWrapper implements LayoutInflater.Factory2 Window ...
- Android Activity学习笔记——Activity的启动和创建
http://www.cnblogs.com/bastard/archive/2012/04/07/2436262.html 最近学习Android相关知识,感觉仅仅了解Activity几个生命周期函 ...
- Android Activity启动流程源码全解析(1)
前言 Activity是Android四大组件的老大,我们对它的生命周期方法调用顺序都烂熟于心了,可是这些生命周期方法到底是怎么调用的呢?在启动它的时候会用到startActivty这个方法,但是这个 ...
随机推荐
- Hibernate学习(二)———— 一级缓存和三种状态解析
一.一级缓存和快照 什么是一级缓存呢? 很简单,每次hibernate跟数据库打交道时,都是通过session来对要操作的对象取得关联,然后在进行操作,那么具体的过程是什么样的呢? 1.首先sessi ...
- js 提交数组到后端(C#)
JS 代码: <script src="~/Scripts/jquery-1.8.2.min.js"></script> <script> // ...
- [PHP] 数据结构-从尾到头打印链表PHP实现
1.遍历后压入反转数组,输出2.array_unshift — 在数组开头插入一个或多个单元,将传入的单元插入到 array 数组的开头int array_unshift ( array &$ ...
- Java 雇员管理小练习(理解面向对象编程)
在学习集合框架的时候,初学者很容易练习到学生管理系统.雇员管理体统等练习题.在学习集合框架之前,基本上Java基本语法都学完了,集合框架也从侧面的检验对前面学习的理解.下面用一个曾经做过的练习题,回顾 ...
- C# Why does '+' + a short convert to 44
I have a line of code that looks like this: MyObject.PhoneNumber = '+' + ThePhonePrefix + TheBizNumb ...
- asynchronous.js
// 异步加载js (function(){ var _asyn_js_data = ['index.js','index1.js','index2.js','index3.js'] for(var ...
- 2017-12-06 JavaScript实现ZLOGO子集: 单层循环功能
前文JavaScript实现ZLOGO子集: 前进+转向的示例代码很累赘, 因此尝试实现基本的循环功能, 使得前面的11行代码缩减为7行: 开始 循环4次 前进200 左转144度 到此为止 前进20 ...
- 【代码笔记】Web-HTML-布局
一, 效果图. 二,代码. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> ...
- jQuery中bind() live() delegate() on() 的区别
实例 bind(type,[data],fn) 为每个匹配元素的特定事件绑定事件处理函数 $("a").bind("click",function(){aler ...
- python练习(-)
简单的爬虫示例: import urllib.request #python2.x版本为urllib2url = 'http://www.douban.com/'webPage=urllib.requ ...