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

相关文章

Go标准库常见错误分析和解决办法

《Go标准库常见错误分析和解决办法》Go语言的标准库为开发者提供了丰富且高效的工具,涵盖了从网络编程到文件操作等各个方面,然而,标准库虽好,使用不当却可能适得其反,正所谓工欲善其事,必先利其器,本文将... 目录1. 使用了错误的time.Duration2. time.After导致的内存泄漏3. jsO

Python实现无痛修改第三方库源码的方法详解

《Python实现无痛修改第三方库源码的方法详解》很多时候,我们下载的第三方库是不会有需求不满足的情况,但也有极少的情况,第三方库没有兼顾到需求,本文将介绍几个修改源码的操作,大家可以根据需求进行选择... 目录需求不符合模拟示例 1. 修改源文件2. 继承修改3. 猴子补丁4. 追踪局部变量需求不符合很

Spring事务中@Transactional注解不生效的原因分析与解决

《Spring事务中@Transactional注解不生效的原因分析与解决》在Spring框架中,@Transactional注解是管理数据库事务的核心方式,本文将深入分析事务自调用的底层原理,解释为... 目录1. 引言2. 事务自调用问题重现2.1 示例代码2.2 问题现象3. 为什么事务自调用会失效3

找不到Anaconda prompt终端的原因分析及解决方案

《找不到Anacondaprompt终端的原因分析及解决方案》因为anaconda还没有初始化,在安装anaconda的过程中,有一行是否要添加anaconda到菜单目录中,由于没有勾选,导致没有菜... 目录问题原因问http://www.chinasem.cn题解决安装了 Anaconda 却找不到 An

Spring定时任务只执行一次的原因分析与解决方案

《Spring定时任务只执行一次的原因分析与解决方案》在使用Spring的@Scheduled定时任务时,你是否遇到过任务只执行一次,后续不再触发的情况?这种情况可能由多种原因导致,如未启用调度、线程... 目录1. 问题背景2. Spring定时任务的基本用法3. 为什么定时任务只执行一次?3.1 未启用

C++ 各种map特点对比分析

《C++各种map特点对比分析》文章比较了C++中不同类型的map(如std::map,std::unordered_map,std::multimap,std::unordered_multima... 目录特点比较C++ 示例代码 ​​​​​​代码解释特点比较1. std::map底层实现:基于红黑

Spring、Spring Boot、Spring Cloud 的区别与联系分析

《Spring、SpringBoot、SpringCloud的区别与联系分析》Spring、SpringBoot和SpringCloud是Java开发中常用的框架,分别针对企业级应用开发、快速开... 目录1. Spring 框架2. Spring Boot3. Spring Cloud总结1. Sprin

Spring 中 BeanFactoryPostProcessor 的作用和示例源码分析

《Spring中BeanFactoryPostProcessor的作用和示例源码分析》Spring的BeanFactoryPostProcessor是容器初始化的扩展接口,允许在Bean实例化前... 目录一、概览1. 核心定位2. 核心功能详解3. 关键特性二、Spring 内置的 BeanFactory

MyBatis-Plus中Service接口的lambdaUpdate用法及实例分析

《MyBatis-Plus中Service接口的lambdaUpdate用法及实例分析》本文将详细讲解MyBatis-Plus中的lambdaUpdate用法,并提供丰富的案例来帮助读者更好地理解和应... 目录深入探索MyBATis-Plus中Service接口的lambdaUpdate用法及示例案例背景

MyBatis-Plus中静态工具Db的多种用法及实例分析

《MyBatis-Plus中静态工具Db的多种用法及实例分析》本文将详细讲解MyBatis-Plus中静态工具Db的各种用法,并结合具体案例进行演示和说明,具有很好的参考价值,希望对大家有所帮助,如有... 目录MyBATis-Plus中静态工具Db的多种用法及实例案例背景使用静态工具Db进行数据库操作插入