之前一段时间项目比较忙所以一直没有更新,接下来准备把插件化系列的文章写完,今天我们就先跳过ContentProvider源码解析来讲资源加载相关的知识,资源加载可以说是插件化非常重要的一环,我们很有必要来了解它。当然看这篇文章之前可以看下性能优化(6)-减小APK体积加深下对资源目录的了解。

一.目标

今天的文章内容是为了插件化框架讲解做准备的知识的,我们的今天要达到的目标是:

1.能明白AssetManager是怎么加载资源的,apk内部或者外部的;

2.同时加深一下对资源的认识。

二.AssetManager

前面我们已经知道因为Activity,ContextWrapper,ContextImpl的关系,这个部分用的是装饰模式来实现的,所以在Activity中调用的大部分方法都将最终调用到ContextImpl中,所以访问资源的两个方法getResources()和getAssets()最终都将调用ContextImpl中的相应方法。

ContextImpl#getResources()方法返回Resources对象,这个对象是根据资源的id来访问相应的资源的,除了assets目录不会在R文件中生成相应的id外,其他都是可以的。ContextImpl#getAssets()返回的是AssetManager对象,这个对象可以根据文件名来返回被编译过或者未编译过的资源。其实Resources对象最终也是通过AssetManager对象来获取资源的,不过会先通过资源id查找到资源文件名。

这里我们首先从ContextImpl#getResources()方法入手:

@Override

public Resources getResources() {

return mResources;

}

我们看到这里直接返回了ContextImpl中的mResources变量,这个变量是在哪里被初始化的呢?我们可以在ContextImpl的构造函数看到:

private ContextImpl(ContextImpl container, ActivityThread mainThread,

LoadedApk packageInfo, IBinder activityToken, UserHandle user, int flags,

Display display, Configuration overrideConfiguration, int createDisplayWithId) {

.....

Resources resources = packageInfo.getResources(mainThread);

....

mResources = resources;

....

}

这里的packageInfo是LoadedApk对象,LoadedApk描述的是当前apk的一些信息,我们看到这个方法首先是调用了LoadedApk#getResources方法,传进去的参数是mainThread,mainThread对应的是ActivityThread对象,也就是当前正在运行的应用程序进程。所以我们接下来看LoadedApk#getResources方法:

public Resources getResources(ActivityThread mainThread) {

if (mResources == null) {

mResources = mainThread.getTopLevelResources(mResDir, mSplitResDirs, mOverlayDirs,

mApplicationInfo.sharedLibraryFiles, Display.DEFAULT_DISPLAY, this);

}

return mResources;

}

这个方法首先会判断mResources是否为空,如果为空才去调用ActivityThread中的方法getTopLevelResources(),这个方法会返回一个Resources对象,其中第一个参数mResDir是资源文件的路径,这个路径就是保存在LoadedApk的变量mResDir中的,第二个参数mSplitResDirs是针对有可能一个app由多个apk组成,每个子apk的资源路径。 mOverlayDirs是目录主题包base.apk的路径,如果没有的话那就为空,mApplicationInfo.sharedLibraryFiles是apk依赖的共享库的文件。接着我们看ActivityThread#getTopLevelResources方法:

Resources getTopLevelResources(String resDir, String[] splitResDirs, String[] overlayDirs,

String[] libDirs, int displayId, LoadedApk pkgInfo) {

return mResourcesManager.getResources(null, resDir, splitResDirs, overlayDirs, libDirs,

displayId, null, pkgInfo.getCompatibilityInfo(), pkgInfo.getClassLoader());

}

我们看到这个方法直接调用ResourcesManager对象的getResources()方法:

public @Nullable Resources getResources(@Nullable IBinder activityToken,

@Nullable String resDir,

@Nullable String[] splitResDirs,

@Nullable String[] overlayDirs,

@Nullable String[] libDirs,

int displayId,

@Nullable Configuration overrideConfig,

@NonNull CompatibilityInfo compatInfo,

@Nullable ClassLoader classLoader) {

try {

Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, "ResourcesManager#getResources");

final ResourcesKey key = new ResourcesKey(

resDir,

splitResDirs,

overlayDirs,

libDirs,

displayId,

overrideConfig != null ? new Configuration(overrideConfig) : null, // Copy

compatInfo);

classLoader = classLoader != null ? classLoader : ClassLoader.getSystemClassLoader();

return getOrCreateResources(activityToken, key, classLoader);

} finally {

Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);

}

}

这个方法会以apk各种资源文件路径为参数创建ResourcesKey对象,接着会讲类加载器赋值给ResourcesManager的变量classLoader,最后会调用getOrCreateResources()方法:

private @Nullable Resources getOrCreateResources(@Nullable IBinder activityToken,

@NonNull ResourcesKey key, @NonNull ClassLoader classLoader) {

synchronized (this) {

.......

if (activityToken != null) {

.......

//根据ResourcesKey来查找

ResourcesImpl resourcesImpl = findResourcesImplForKeyLocked(key);

if (resourcesImpl != null) {

if (DEBUG) {

Slog.d(TAG, "- using existing impl=" + resourcesImpl);

}

//如果 resourcesImpl 有 那么根据resourcesImpl 和classLoader 从缓存

//ActivityResources中的activityResources找找 Resource

return getOrCreateResourcesForActivityLocked(activityToken, classLoader,

resourcesImpl);

}

// We will create the ResourcesImpl object outside of holding this lock.

} else {

.......

}

// If we're here, we didn't find a suitable ResourcesImpl to use, so create one now.

//这个方法等会会重点来看,这里是因为前面未找到合适的ResourcesImpl ,所以这里

//会用ResourceKey来创建

ResourcesImpl resourcesImpl = createResourcesImpl(key);

if (resourcesImpl == null) {

return null;

}

synchronized (this) {

ResourcesImpl existingResourcesImpl = findResourcesImplForKeyLocked(key);

if (existingResourcesImpl != null) {

if (DEBUG) {

Slog.d(TAG, "- got beat! existing impl=" + existingResourcesImpl

+ " new impl=" + resourcesImpl);

}

resourcesImpl.getAssets().close();

resourcesImpl = existingResourcesImpl;

} else {

// Add this ResourcesImpl to the cache.

mResourceImpls.put(key, new WeakReference<>(resourcesImpl));

}

final Resources resources;

if (activityToken != null) {

//根据classloader和resourcesImpl来获取Resources对象

resources = getOrCreateResourcesForActivityLocked(activityToken, classLoader,

resourcesImpl);

} else {

resources = getOrCreateResourcesLocked(classLoader, resourcesImpl);

}

return resources;

}

}

我们看到这个方法会先根据ResourcesKey查找ResourcesImpl对象,如果能找到的话,那么就会根据ResourcesImpl对象和classloader来获取Resource对象。如果没找到ResourcesImpl对象的话,那么会调用createResourcesImpl()方法创建。最后依然根据ResourcesImpl对象和classloader来获取Resource对象。我们这里再来看看createResourcesImpl()方法:

private @Nullable ResourcesImpl createResourcesImpl(@NonNull ResourcesKey key) {

final DisplayAdjustments daj = new DisplayAdjustments(key.mOverrideConfiguration);

daj.setCompatibilityInfo(key.mCompatInfo);

//创建 AssetManager 对象

final AssetManager assets = createAssetManager(key);

if (assets == null) {

return null;

}

final DisplayMetrics dm = getDisplayMetrics(key.mDisplayId, daj);

final Configuration config = generateConfig(key, dm);

//根据AssetManager 创建一个ResourcesImpl。所以查找资源的话就会查找到Resources

//然后ResourcesImpl,最后就是到AssetManager

final ResourcesImpl impl = new ResourcesImpl(assets, dm, config, daj);

if (DEBUG) {

Slog.d(TAG, "- creating impl=" + impl + " with key: " + key);

}

return impl;

}

这个方法里面有一个很重要的方法那就是createAssetManager()方法,这个方法会返回AssetManager对象,我们来看下这个方法:

@VisibleForTesting

protected @Nullable AssetManager createAssetManager(@NonNull final ResourcesKey key) {

AssetManager assets = new AssetManager();

// resDir can be null if the 'android' package is creating a new Resources object.

// This is fine, since each AssetManager automatically loads the 'android' package

// already.

if (key.mResDir != null) {

if (assets.addAssetPath(key.mResDir) == 0) {

Log.e(TAG, "failed to add asset path " + key.mResDir);

return null;

}

}

if (key.mSplitResDirs != null) {

for (final String splitResDir : key.mSplitResDirs) {

if (assets.addAssetPath(splitResDir) == 0) {

Log.e(TAG, "failed to add split asset path " + splitResDir);

return null;

}

}

}

if (key.mOverlayDirs != null) {

for (final String idmapPath : key.mOverlayDirs) {

assets.addOverlayPath(idmapPath);

}

}

if (key.mLibDirs != null) {

for (final String libDir : key.mLibDirs) {

if (libDir.endsWith(".apk")) {

// Avoid opening files we know do not have resources,

// like code-only .jar files.

if (assets.addAssetPathAsSharedLibrary(libDir) == 0) {

Log.w(TAG, "Asset path '" + libDir +

"' does not exist or contains no resources.");

}

}

}

}

return assets;

}

上面的方法我们可以很清楚看到这个方法分别调用了AssetManager对象的addAssetPath,addOverlayPath,addAssetPathAsSharedLibrary方法,这些方法都是native的方法,我们不去细看,这几个方法就是分别加载相应资源文件路径的资源。其中addAssetPathAsSharedLibrary方法调用之前还会判断是不是以apk开头的,是因为jar文件中不能包含资源文件。我们最后看下获取了ResourcesImpl对象之后,由于activityToken 为null,所以最终会调用getOrCreateResourcesLocked方法:

private @NonNull Resources getOrCreateResourcesLocked(@NonNull ClassLoader classLoader,

@NonNull ResourcesImpl impl) {

// Find an existing Resources that has this ResourcesImpl set.

final int refCount = mResourceReferences.size();

for (int i = 0; i < refCount; i++) {

//在Resources的弱引用中查找

WeakReference weakResourceRef = mResourceReferences.get(i);

Resources resources = weakResourceRef.get();

if (resources != null &&

Objects.equals(resources.getClassLoader(), classLoader) &&

resources.getImpl() == impl) {

if (DEBUG) {

Slog.d(TAG, "- using existing ref=" + resources);

}

return resources;

}

}

// Create a new Resources reference and use the existing ResourcesImpl object.

// 创建一个Resources ,Resource有好几个构造方法,每个版本之间有稍微的差别

// 有的版本是用的这一个构造方法 Resources(assets, dm, config, compatInfo)

Resources resources = new Resources(classLoader);

resources.setImpl(impl);

mResourceReferences.add(new WeakReference<>(resources));

if (DEBUG) {

Slog.d(TAG, "- creating new ref=" + resources);

Slog.d(TAG, "- setting ref=" + resources + " with impl=" + impl);

}

return resources;

}

我们看到创建好ResourcesImpl之后会再去缓存中找Resource如果没有,那么则会创建Resource并将其缓存。到这里我们的加载资源部分已经完毕,我们可以看到我们如果要加载外部的资源文件,我们可以反射调用AssetManager#addAssetPath方法来加载我们自己的资源文件。这个地方到时会详细讲解,现在只要有个意识就可以。

总结:到这里资源的加载就已经讲完了,我们下一篇要写资源的查找过程,大家就当扩展一下知识,希望大家在这个系列的文章中能有所收获,不正确的欢迎指出,虚心接受。

android资源加载流程6,FrameWork源码解析(6)-AssetManager加载资源过程相关推荐

  1. Framework 源码解析知识梳理(5) startService 源码分析

    一.前言 最近在看关于插件化的知识,遇到了如何实现Service插件化的问题,因此,先学习一下Service内部的实现原理,这里面会涉及到应用进程和ActivityManagerService的通信, ...

  2. Android View体系(五)从源码解析View的事件分发机制

    Android View体系(一)视图坐标系 Android View体系(二)实现View滑动的六种方法 Android View体系(三)属性动画 Android View体系(四)从源码解析Sc ...

  3. Android多页蒙版遮罩引导功能(源码+解析)

    #Android多页蒙版遮罩引导功能(源码+解析) 需求:博主前段时间做的教育类型APP,需要引导用户(低龄化小朋友),播放器的播放,页面可以左右滑动,以及右上方进入答题卡入口(小朋友都是很聪明的,引 ...

  4. 从源码解析-结合Activity加载流程深入理解ActivityThrad的工作逻辑

    ActivityThread源码解析 前言 类简称 类简介 一 二 三 四 五 代理和桩的理解 ActivityThread ActivityThread.main AT.attach AMN.get ...

  5. 【框架源码】Spring源码解析之BeanDefinition加载流程解析

    观看本文之前,我们先思考一个问题,Spring是如何描述Bean对象的? Spring是根据BeanDefinition来创建Bean对象,BeanDefinition就是Spring中表示Bean定 ...

  6. tomcat热加载、热部署-源码解析

    上文:tomcat线程模型-源码解析 热加载和热部署是什么? 请查看原来的写过的文章:热部署和热加载有什么区别? tomcat热加载和执热部署都是通过后台进程检测项目中的.class和目录是否发生变化 ...

  7. Android View体系(六)从源码解析Activity的构成

    前言 本来这篇是要讲View的工作流程的,View的工作流程主要指的measure.layout.draw这三大流程,在讲到这三大流程之前我们有必要要先了解下Activity的构成,所以就有了这篇文章 ...

  8. 谷歌BERT预训练源码解析(三):训练过程

    目录 前言 源码解析 主函数 自定义模型 遮蔽词预测 下一句预测 规范化数据集 前言 本部分介绍BERT训练过程,BERT模型训练过程是在自己的TPU上进行的,这部分我没做过研究所以不做深入探讨.BE ...

  9. Spring AOP源码解析-拦截器链的执行过程

    一.简介 在前面的两篇文章中,分别介绍了 Spring AOP 是如何为目标 bean 筛选合适的通知器,以及如何创建代理对象的过程.现在得到了 bean 的代理对象,且通知也以合适的方式插在了目标方 ...

最新文章

  1. 易扩展的SLAM框架-OpenVSLAM
  2. python输入语句-python输入语句
  3. bzoj2190 [SDOI2008]仪仗队(欧拉函数)
  4. python编程怎么做游戏主播_如何成为一名成功的编程主播?
  5. 使用cmake重写live555工程-附源码和视频教程
  6. Razor 中的@rendersection
  7. 通俗演义TCP流量控制
  8. MySQL - ERROR 1406
  9. HTML - 文本及其格式化
  10. 用ie浏览器签章后保存在桌面显示不出文件
  11. python中response是什么意思_python中的requests,response.text与response.content ,及其编码
  12. matlab实现色彩迁移,图像的色彩风格迁移
  13. java web 组态,Java:Eclipse中使用WTP开发Web项目
  14. matlab不能定位,matlab定位问题!
  15. vivado生成bit流错误:Combinatorial Loop Alert
  16. 结对项目:SudokuGame
  17. TSP问题的解法(java版)
  18. Excel中VLOOKUP函数简易使用——精确匹配或近似匹配数据
  19. 首席新媒体黎想教程:SEO中的反向链接是什么意思?
  20. (VKL系列)超低功耗LCD液晶显示驱动IC-VKL076 SSOP28,19*4 76点阵,超低工作电流约7.5微安,适用水电表/温湿度计/温控器/传感器等,FAE技术支持

热门文章

  1. CorelDraw插件开发-VBA-常用功能-裁切阴影效果图形-CDR插件
  2. vr制作软件是什么,常用都是哪几个?
  3. uaa 授权_使用UAA引导OAuth2授权服务器
  4. 数据分析对淘宝店铺有什么作用?
  5. python怎么向上取整
  6. C语言I博客作业 04
  7. js控制回车触发事件
  8. unity 刘海全面屏适配
  9. mac无法读取U盘怎么办?如何让U盘同时在Mac和Windows系统下打开
  10. oak深度相机入门教程-疲劳状态检测