Framework源码分析(三):ActivityThread

2024-06-05 16:18

本文主要是介绍Framework源码分析(三):ActivityThread,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在ActivityManagerService这一篇博客中,我们已经了解AMS在Android系统中是管理系统中Activity的重要类,他通过Binder进程间通信的方式去调度Activity,从而操作Activity的生命周期。那么在这一篇博客中,我们继续通过认识ActivityThread来进一步了解Activity的创建和启动的原理。

简述App启动流程

APP启动流程

从图中的流程来看,首先用户在Android桌面中发起针对某个应用程序的点击事件之后:
(1)LauncherActivity通过Binder进程间通信的方式将应用的信息通过Intent的方式传递给AMS,由AMS进行调度。
(2)如果系统中不存在该进程时,AMS将会请求Zygote服务去fork一个子进程,成功后返回一个pid给AMS,并由AndroidRuntime机制调起ActivityThread中的main()方法。
(3)紧接着,应用程序的Main Looper被创建,ActivityThread被实例化成为对象并将Application的信息以进程间通信的方式再次回馈给AMS。
(4)AMS接收到客户端发来的请求数据之后,首先将应用程序绑定,并启动应用程序的Activity,开始执行Activity的生命周期。

1. 应用程序的入口

ActivityThread的Main方法是应用程序进程的入口。先贴上代码:

    public static void main(String[] args) {Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");SamplingProfilerIntegration.start();// CloseGuard defaults to true and can be quite spammy.  We// disable it here, but selectively enable it later (via// StrictMode) on debug builds, but using DropBox, not logs.CloseGuard.setEnabled(false);Environment.initForCurrentUser();// Set the reporter for event logging in libcoreEventLogger.setReporter(new EventLoggingReporter());// Make sure TrustedCertificateStore looks in the right place for CA certificatesfinal File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());TrustedCertificateStore.setDefaultUserDirectory(configDir);Process.setArgV0("<pre-initialized>");Looper.prepareMainLooper();ActivityThread thread = new ActivityThread();thread.attach(false);if (sMainThreadHandler == null) {sMainThreadHandler = thread.getHandler();}if (false) {Looper.myLooper().setMessageLogging(newLogPrinter(Log.DEBUG, "ActivityThread"));}// End of event ActivityThreadMain.Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);Looper.loop();throw new RuntimeException("Main thread loop unexpectedly exited");}

在这里需要解释一下,这部分代码都干了哪些事儿:
(1)初始化应用程序中需要使用到的系统路径

Environment.initForCurrentUser();

(2)设置进程名称

Process.setArgV0("<pre-initialized>");

(3)在这里为应用程序的主线程创建了Looper。

Looper.prepareMainLooper();

thread.getHandler()保存了主线程的Handler

if (sMainThreadHandler == null) {sMainThreadHandler = thread.getHandler(); 
}

通过Looper.loop()的调用进入消息循环

Looper.loop();

(4)实例化ActivityThread对象,并通过attach()方法将APP的信息通过进程间通信的方式传递给AMS进行绑定。在下面我们会详细的讲下attach()方法。

ActivityThread thread = new ActivityThread();
thread.attach(false);

2. ApplicationThread

在attach()方法中,可以找到如下代码:

private void attach(boolean system) {sCurrentActivityThread = this;mSystemThread = system;if (!system) {...// 以上省略RuntimeInit.setApplicationObject(mAppThread.asBinder());final IActivityManager mgr = ActivityManagerNative.getDefault();try {mgr.attachApplication(mAppThread);} catch (RemoteException ex) {throw ex.rethrowFromSystemServer();}...// 以下省略}
}
// 实例化应用程序进程对象
final ApplicationThread mAppThread = new ApplicationThread();

首先,将mAppThread对象转换成为binder对象并将其作为应用程序先report给VM,该应用程序就能够获得VM反馈的一些异常和错误。然后通过获得Client端的代理对象,将mAppThread对象作为参数传递给AMS进行调度处理。

ApplicationThread继承了ApplicationThreadNative类,而ApplicationThreadNative又继承了Binder,那么它就拥有了进程间通信的特质,于此同时它最终又实现了IApplicationThread接口,该接口实现了操作App生命周期的各种方法回调。

    @Overridepublic final void attachApplication(IApplicationThread thread) {synchronized (this) {int callingPid = Binder.getCallingPid();final long origId = Binder.clearCallingIdentity();attachApplicationLocked(thread, callingPid);Binder.restoreCallingIdentity(origId);}}
    private final boolean attachApplicationLocked(IApplicationThread thread,int pid) {// Find the application record that is being attached...  either via// the pid if we are running in multiple processes, or just pull the// next app record if we are emulating process with anonymous threads....// 省略以上部分代码try {ProfilerInfo profilerInfo = profileFile == null ? null: new ProfilerInfo(profileFile, profileFd, samplingInterval, profileAutoStop);// 通过AMS调用bindApplication()方法将进程绑定thread.bindApplication(processName, appInfo, providers, app.instrumentationClass,profilerInfo, app.instrumentationArguments, app.instrumentationWatcher,app.instrumentationUiAutomationConnection, testMode,mBinderTransactionTrackingEnabled, enableTrackAllocation,isRestrictedBackupMode || !normalMode, app.persistent,new Configuration(mConfiguration), app.compat,getCommonServicesLocked(app.isolated),mCoreSettingsObserver.getCoreSettingsLocked());updateLruProcessLocked(app, false, null);app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();} catch (Exception e) {// todo: Yikes!  What should we do?  For now we will try to// start another process, but that could easily get us in// an infinite loop of restarting processes...Slog.wtf(TAG, "Exception thrown during bind of " + app, e);app.resetPackageList(mProcessStats);app.unlinkDeathRecipient();startProcessLocked(app, "bind fail", processName);return false;}... // 省略以下部分代码return true;}

AMS拿到mAppThread的对象之后,首先调用bindApplication()的方法将应用程序绑定,并通过应用程序发送的Activity生命周期的信号对应实现Activity生命周期的操作。

在这里大家可能会思考一个问题就是:Activity是如何执行自己的生命周期的。这个问题我先给自己埋一个坑,在未来的文章中,我把这个问题作为一个章节继续深入讲解。

这篇关于Framework源码分析(三):ActivityThread的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1033549

相关文章

python使用Akshare与Streamlit实现股票估值分析教程(图文代码)

《python使用Akshare与Streamlit实现股票估值分析教程(图文代码)》入职测试中的一道题,要求:从Akshare下载某一个股票近十年的财务报表包括,资产负债表,利润表,现金流量表,保存... 目录一、前言二、核心知识点梳理1、Akshare数据获取2、Pandas数据处理3、Matplotl

python panda库从基础到高级操作分析

《pythonpanda库从基础到高级操作分析》本文介绍了Pandas库的核心功能,包括处理结构化数据的Series和DataFrame数据结构,数据读取、清洗、分组聚合、合并、时间序列分析及大数据... 目录1. Pandas 概述2. 基本操作:数据读取与查看3. 索引操作:精准定位数据4. Group

MySQL中EXISTS与IN用法使用与对比分析

《MySQL中EXISTS与IN用法使用与对比分析》在MySQL中,EXISTS和IN都用于子查询中根据另一个查询的结果来过滤主查询的记录,本文将基于工作原理、效率和应用场景进行全面对比... 目录一、基本用法详解1. IN 运算符2. EXISTS 运算符二、EXISTS 与 IN 的选择策略三、性能对比

MySQL 内存使用率常用分析语句

《MySQL内存使用率常用分析语句》用户整理了MySQL内存占用过高的分析方法,涵盖操作系统层确认及数据库层bufferpool、内存模块差值、线程状态、performance_schema性能数据... 目录一、 OS层二、 DB层1. 全局情况2. 内存占js用详情最近连续遇到mysql内存占用过高导致

深度解析Nginx日志分析与499状态码问题解决

《深度解析Nginx日志分析与499状态码问题解决》在Web服务器运维和性能优化过程中,Nginx日志是排查问题的重要依据,本文将围绕Nginx日志分析、499状态码的成因、排查方法及解决方案展开讨论... 目录前言1. Nginx日志基础1.1 Nginx日志存放位置1.2 Nginx日志格式2. 499

Olingo分析和实践之EDM 辅助序列化器详解(最佳实践)

《Olingo分析和实践之EDM辅助序列化器详解(最佳实践)》EDM辅助序列化器是ApacheOlingoOData框架中无需完整EDM模型的智能序列化工具,通过运行时类型推断实现灵活数据转换,适用... 目录概念与定义什么是 EDM 辅助序列化器?核心概念设计目标核心特点1. EDM 信息可选2. 智能类

Olingo分析和实践之OData框架核心组件初始化(关键步骤)

《Olingo分析和实践之OData框架核心组件初始化(关键步骤)》ODataSpringBootService通过初始化OData实例和服务元数据,构建框架核心能力与数据模型结构,实现序列化、URI... 目录概述第一步:OData实例创建1.1 OData.newInstance() 详细分析1.1.1

Olingo分析和实践之ODataImpl详细分析(重要方法详解)

《Olingo分析和实践之ODataImpl详细分析(重要方法详解)》ODataImpl.java是ApacheOlingoOData框架的核心工厂类,负责创建序列化器、反序列化器和处理器等组件,... 目录概述主要职责类结构与继承关系核心功能分析1. 序列化器管理2. 反序列化器管理3. 处理器管理重要方

SpringBoot中六种批量更新Mysql的方式效率对比分析

《SpringBoot中六种批量更新Mysql的方式效率对比分析》文章比较了MySQL大数据量批量更新的多种方法,指出REPLACEINTO和ONDUPLICATEKEY效率最高但存在数据风险,MyB... 目录效率比较测试结构数据库初始化测试数据批量修改方案第一种 for第二种 case when第三种

解决1093 - You can‘t specify target table报错问题及原因分析

《解决1093-Youcan‘tspecifytargettable报错问题及原因分析》MySQL1093错误因UPDATE/DELETE语句的FROM子句直接引用目标表或嵌套子查询导致,... 目录报js错原因分析具体原因解决办法方法一:使用临时表方法二:使用JOIN方法三:使用EXISTS示例总结报错原