Android Activity.startActivity流程简介

article/2025/11/5 6:00:38

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;

    其功能函数下表所示:

功能函数
增加删除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启动流程如下所示:

/****************************************************************** 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 ActivityManagerNativeimplements 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); // 创建ActivityStackm.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 processfinal boolean isolated;     // true if this is a special isolated processfinal int uid;              // uid of process; may be different from 'info' if isolatedfinal int userId;           // user of process.final String processName;   // name of the processIApplicationThread 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 noneApplicationInfo instrumentationInfo; // the application being instrumentedBroadcastRecord curReceiver;// receiver currently running in the app// contains HistoryRecord objectsfinal ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();// all ServiceRecord running in this processfinal 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 holdsfinal HashSet<ConnectionRecord> connections= new HashSet<ConnectionRecord>();  // all IIntentReceivers that are registered from this process.final HashSet<ReceiverList> receivers = new HashSet<ReceiverList>();// class (String) -> ContentProviderRecordfinal HashMap<String, ContentProviderRecord> pubProviders= new HashMap<String, ContentProviderRecord>(); // All ContentProviderRecord process is usingfinal 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 dialogProcessRecord(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中对应的接口函数。

   其相互关系如下图所示:













http://chatgpt.dhexx.cn/article/OJFb6I79.shtml

相关文章

android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context

问题描述 FATAL EXCEPTION: main Process: com.wuchen.juexiao_mvvm, PID: 11732 android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want? 原因分析…

Android主线程(ActivityThread)源代码分析

在写这篇博客之前,先抛出一个问题&#xff0c;安卓应用程序的入口是什么呢&#xff1f;我想不少人可能回答说:application的onCreate方法&#xff0c;其实并不是的&#xff0c;即使是application&#xff0c;也有一个方法比onCreate先执行&#xff0c;这个方法就是attachBaseCo…

Android :Activity

Activity Activity 代表手机或平板电脑中的一屏&#xff0c;它提供了和用户交互的可视化界面。 一个 Android 应用中&#xff0c;可以有多个 Activity。这些 Activity 组成了 Activity 栈&#xff08;Stack&#xff09;&#xff0c;当前活动的 Activity 位于栈顶。 Activity …

ActivityThread

ActivityThread运行框架 在分析中&#xff0c;我们可以看到真正对应应用进程的不是Application而是ActivityThread。我们从实际的应用堆栈可以看到&#xff1a; NaiveStart.main() ZygoteInit.main ZygoteInit$MethodAndArgsCall.run Method.Invoke method.invokeNative Activi…

【Android 启动过程】Activity 启动源码分析 ( AMS -> ActivityThread、AMS 线程阶段 )

文章目录 一、Activity 启动源码分析 ( AMS | ActivityManagerService )1、Instrumentation 调用 AMS 方法2、ActivityStarter 调用 AMS 方法3、Process 启动新进程 二、Activity 启动源码分析 ( ActivityStarter )1、ActivityStarter.startActivityMayWait() 方法2、ActivityS…

Android 中你碰不到但是很重要的类之ActivityThread

作者&#xff1a;Drummor 通过本文能了解一下内容 1、和系统进程打交道的桥头堡 应用进程起来之后ART(Android Runtime)第一站就是ActivityThread&#xff0c;代码层面上就是ActivityThread的main()方法&#xff0c;是不是很熟悉&#xff0c;爷青回啊&#xff0c;这不就是java…

浅析ActivityThread#main()方法和生命周期事务处理(代码基于Android-12)

浅析ActivityThread#main()方法和生命周期事务处理&#xff08;代码基于Android-12&#xff09; 问题&#xff1a; Activity、Application的onCreate()在哪被调用的&#xff1f; ContentProvider为什么比Application先创建&#xff1f; Activity#attach()在哪里被调用的&#…

Android中的ActivityThread和ApplicationThread

一&#xff1a;ActivityThread和ApplicationThread 1.ActivityThread&#xff1a;主线程、UI线程&#xff0c;程序的入口&#xff08;main函数&#xff09;&#xff0c;不是线程是运行在主线程中的一个对象 主要的成员变量如下&#xff1a; mActivities、mServices和mProvide…

一文读懂ActivityThread

ActivityThread是什么&#xff0c;是主线程吗&#xff1f;它是如何被创建的&#xff0c;以及它的作用又是什么呢&#xff1f;带着这些问题&#xff0c;我们一起来分析下ActivityThread。 全文分为以下几个部分&#xff0c;大家可根据需求阅读 文章目录 ActivityThread是什么Act…

Android ActivityThread(主线程或UI线程)简介

1. ActivityThread功能 它管理应用进程的主线程的执行(相当于普通Java程序的main入口函数)&#xff0c;并根据AMS的要求&#xff08;通过IApplicationThread接口&#xff0c;AMS为Client、ActivityThread.ApplicationThread为Server&#xff09;负责调度和执行activities、broa…

ActivityThread的理解和APP的启动过程

ActivityThread的理解和APP的启动过程 ActivityThreadActivityThread的初始化主线程Looper的初始化主线程Handler的初始化ApplicationThread及Activity的创建和启动 APP的启动系统的启动过程APP的启动过程APP启动过程的部分代码思考 总结 ActivityThread ActivityThread就是我…

validate中remote返回函数中+号导致submitHandler无法执行

validate中remote返回函数中号导致submitHandler无法执行 这是2017年以来我遇到的最无语的bug&#xff0c;现在暂时还没想到原因&#xff0c;但是这个错误真的很无语。 这是我的validate中rule的定义&#xff0c;其中 new Date; 采用至慕课网上validate插件视频中的例子。 rul…

jQuery(六)插件、Validate验证提交表单、submitHandler、更改错误信息显示的位置、required、Validator、内置验证方式表、validate ()的可选项汇总

jQuery&#xff08;六&#xff09;插件、Validate验证提交表单、submitHandler、更改错误信息显示的位置、required、Validator、内置验证方式表、validate ()的可选项汇总 文章目录 jQuery&#xff08;六&#xff09;插件、Validate验证提交表单、submitHandler、更改错误信息…

ajax post 不起作用,jQuery验证submitHandler在$ .ajax post表单数据中不起作用

我使用$.ajax发送数据并使用jQuery验证插件进行验证&#xff0c;如下所示&#xff1a; Send JS&#xff1a; jQuery(document).ready(function ($) { $(#myform).validate({ rules: { name: { required: true, rangelength: [4, 20], }, }, submitHandler: function (form) { $…

FileReader()用法

FileReader()用法HTML5定义了FileReader作为文件API的重要成员用于读文件&#xff0c;根据W3C的定义&#xff0c;FileReaderr接口提供了读取文件的方法和包含读取 结果的事件模型。 FileReader的方法使用比较简单&#xff0c;可以按照以下步骤创建FileReader对象并调用其他的方…

read/write/fsync与fread/fwrite/fflush的关系和区别

read/write/fsync&#xff1a; 1. linux底层操作&#xff1b; 2. 内核调用&#xff0c; 涉及到进程上下文的切换&#xff0c;即用户态到核心态的转换&#xff0c;这是个比较消耗性能的操作。 fread/fwrite/fflush&#xff1a; 1. c语言标准规定的io流操作&#xff0c;建立…

FileReader详解

我在Google Chrome Web Store上发布了一个案例hahaOCR&#xff0c;该扩展程序可以帮助用户识别出图片中的文字信息&#xff0c;并以文本形式显示&#xff0c;大家可以在chrome网上应用商店中找到我发布的应用程序&#xff0c;如图所示&#xff1a; 图1 - hahaOCR 该扩展程序支持…

f.readlines()

f.readlines() ftext open(1299_wangyifei_edit.pinyin, r, encodingutf-8)lines ftext.readlines()print("lines",lines)l ftext.readlines()print("l",l)输出结果&#xff1a; 原因&#xff1a; readlines() 方法用于读取所有行(直到结束符 EOF)并返…

FileReader的用法

FileReader是一种异步文件读取机制&#xff0c;结合input:file可以很方便的读取本地文件。 input:file input的file类型会渲染为一个按钮和一段文字。点击按钮可打开文件选择窗口&#xff0c;文字表示对文件的描述&#xff08;大部分情况下为文件名&#xff09;&#xff1b;…

【原创】通过 ioctl + FIONREAD 判定数据可读

【原创】通过 ioctl FIONREAD 判定数据可读 摩云飞 2016-05-12 09:57:51 浏览470 评论0 libevent ioctl FIONREAD 摘要&#xff1a; 在排查业务 bug 的过程中&#xff0c;看到如下两种输出信息&#xff1a; TCP 连接正常情况下&#xff0c;进行数据读取 14:00:38 epoll_ctl…