源码解析:可能是全网最细的Android-资源加载机制剖析,墙裂建议收藏(1)

本文详细描述了Android系统中如何根据资源ID从XML文件、资产管理器和预加载资源中加载Drawable对象的过程,涉及TypedValue、AssetManager的使用和资源路径管理。
摘要由CSDN通过智能技术生成

cs = sPreloadedDrawables[mConfiguration.getLayoutDirection()].get(key);
}

//创建Drawable
Drawable dr;
if (cs != null) {
dr = cs.newDrawable(wrapper);
} else if (isColorDrawable) {
dr = new ColorDrawable(value.data);
} else {
dr = loadDrawableForCookie(wrapper, value, id, null);
}

// 对Drawable的主题进行处理
final boolean canApplyTheme = dr != null && dr.canApplyTheme();
if (canApplyTheme && theme != null) {
dr = dr.mutate();
dr.applyTheme(theme);
dr.clearMutated();
}

// 将装载的Drawable资源加入到缓存之中
if (dr != null && useCache) {
dr.setChangingConfigurations(value.changingConfigurations);
cacheDrawable(value, isColorDrawable, caches, theme, canApplyTheme, key, dr);
}
return dr;
} catch (Exception e) {

}
}

loadDrawableForCookie

根据TypedValue中存储的信息,从XML文件或者资源流中构建Drawable

private Drawable loadDrawableForCookie(Resources wrapper, TypedValue value, int id,
Resources.Theme theme) {
if (value.string == null) {
throw new NotFoundException(“Resource “” + getResourceName(id) + “” (”

  • Integer.toHexString(id) + ") is not a Drawable (color or path): " + value);
    }
    //解析值的文件名
    final String file = value.string.toString();

if (TRACE_FOR_MISS_PRELOAD) {
// Log only framework resources
if ((id >>> 24) == 0x1) {
final String name = getResourceName(id);
if (name != null) {
Log.d(TAG, “Loading framework drawable #” + Integer.toHexString(id)

  • ": " + name + " at " + file);
    }
    }
    }

final Drawable dr;
//如果文件后缀为xml,通过XmlResourceParser构建Drawable对象
try {
if (file.endsWith(“.xml”)) {
final XmlResourceParser rp = loadXmlResourceParser(
file, id, value.assetCookie, “drawable”);
dr = Drawable.createFromXml(wrapper, rp, theme);
rp.close();
} else {
//从文件流中构建Drawable对象
final InputStream is = mAssets.openNonAsset(
value.assetCookie, file, AssetManager.ACCESS_STREAMING);
dr = Drawable.createFromResourceStream(wrapper, value, is, file, null);
is.close();
}
} catch (Exception e) {

}
return dr;
}

XmlResourceParser loadXmlResourceParser(@NonNull String file, @AnyRes int id, int assetCookie,
@NonNull String type)
throws NotFoundException {
if (id != 0) {
try {
synchronized (mCachedXmlBlocks) {
final int[] cachedXmlBlockCookies = mCachedXmlBlockCookies;
final String[] cachedXmlBlockFiles = mCachedXmlBlockFiles;
final XmlBlock[] cachedXmlBlocks = mCachedXmlBlocks;
// 检测缓存是否在我们需要的资源
final int num = cachedXmlBlockFiles.length;
for (int i = 0; i < num; i++) {
if (cachedXmlBlockCookies[i] == assetCookie && cachedXmlBlockFiles[i] != null
&& cachedXmlBlockFiles[i].equals(file)) {
return cachedXmlBlocks[i].newParser();
}
}

// 如果资源不在缓存之中,这通过AssetManager去装载,然后加入到缓存中
final XmlBlock block = mAssets.openXmlBlockAsset(assetCookie, file);
if (block != null) {
final int pos = (mLastCachedXmlBlockIndex + 1) % num;
mLastCachedXmlBlockIndex = pos;
final XmlBlock oldBlock = cachedXmlBlocks[pos];
if (oldBlock != null) {
oldBlock.close();
}
cachedXmlBlockCookies[pos] = assetCookie;
cachedXmlBlockFiles[pos] = file;
cachedXmlBlocks[pos] = block;
return block.newParser();
}
}
} catch (Exception e) {

}
}
}

图片资源的装载流程是首先将根据ID获得TypedValue实例,然后根据TypedValue进行查找Drawable资源,首先检测缓存中是否有该资源,如果没有从预加载资源中查找,如果预加载资源中也没有,判断要加载的资源类型,如果为colorDrawable,这根据Typedvalue进行创建,否则通过加载xml或者文件输入流进行处理来获得Drawable对象。

资源的装载分为两步,一个是通过资源ID得到ID对应的TypedValue对象,对于简单的资源,通过TypedValue即可,对于复杂的资源,需要第二步来把资源文件装载到内存之中。

AssetManager

在创建Resources的构造函数,创建ResourcesImpl的时候调用了AssetManager的getSystem方法,该方法用来确保创建唯一的AssetManager实例。

public static AssetManager getSystem() {
ensureSystemAssets();
return sSystem;
}

保证全局只有一个AssetManager

private static void ensureSystemAssets() {
synchronized (sSync) {
if (sSystem == null) {
AssetManager system = new AssetManager(true);
system.makeStringBlocks(null);
sSystem = system;
}
}
}

private AssetManager(boolean isSystem) {
if (DEBUG_REFS) {
synchronized (this) {
mNumRefs = 0;
incRefsLocked(this.hashCode());
}
}
init(true);
}

static void android_content_AssetManager_init(JNIEnv* env, jobject clazz, jboolean isSystem)
{
if (isSystem) {
verifySystemIdmaps();
}
AssetManager* am = new AssetManager();
if (am == NULL) {
jniThrowException(env, “java/lang/OutOfMemoryError”, “”);
return;
}

am->addDefaultAssets();

ALOGV(“Created AssetManager %p for Java object %p\n”, am, clazz);
env->SetLongField(clazz, gAssetManagerOffsets.mObject, reinterpret_cast(am));
}

bool AssetManager::addDefaultAssets()
{
const char* root = getenv(“ANDROID_ROOT”);
LOG_ALWAYS_FATAL_IF(root == NULL, “ANDROID_ROOT not set”);

String8 path(root);
path.appendPath(kSystemAssets);

return addAssetPath(path, NULL, false /* appAsLib /, true / isSystemAsset */);
}

设置资源路径,通过对这个值的修改可以实现动态加载。

public final int addAssetPath(String path) {
return addAssetPathInternal(path, false);
}

private final int addAssetPathInternal(String path, boolean appAsLib) {
synchronized (this) {
int res = addAssetPathNative(path, appAsLib);
makeStringBlocks(mStringBlocks);
return res;
}
}

添加资源路径

bool AssetManager::addAssetPath(
const String8& path, int32_t* cookie, bool appAsLib, bool isSystemAsset)
{
AutoMutex _l(mLock);

asset_path ap;

String8 realPath(path);
if (kAppZipName) {
realPath.appendPath(kAppZipName);
}
ap.type = ::getFileType(realPath.string());
if (ap.type == kFileTypeRegular) {
ap.path = realPath;
} else {
ap.path = path;
ap.type = ::getFileType(path.string());
if (ap.type != kFileTypeDirectory && ap.type != kFileTypeRegular) {
ALOGW(“Asset path %s is neither a directory nor file (type=%d).”,
path.string(), (int)ap.type);
return false;
}
}

// Skip if we have it already.
for (size_t i=0; i<mAssetPaths.size(); i++) {
if (mAssetPaths[i].path == ap.path) {
if (cookie) {
*cookie = static_cast<int32_t>(i+1);
}
return true;
}
}

ALOGV(“In %p Asset %s path: %s”, this,
ap.type == kFileTypeDirectory ? “dir” : “zip”, ap.path.string());

ap.isSystemAsset = isSystemAsset;
mAssetPaths.add(ap);

// new paths are always added at the end
if (cookie) {
*cookie = static_cast<int32_t>(mAssetPaths.size());
}

#ifdef ANDROID
// Load overlays, if any
asset_path oap;
for (size_t idx = 0; mZipSet.getOverlay(ap.path, idx, &oap); idx++) {
oap.isSystemAsset = isSystemAsset;
mAssetPaths.add(oap);
}
#endif

if (mResources != NULL) {
appendPathToResTable(ap, appAsLib);
}

return true;
}

APK文件中有一个文件resource.arsc。这个文件存放的是APK中资源的ID和资源类型,属性,文件名的读经关系表和所有的字符串,装载APK,就是解析该文件生成ResRTable对象,通过ResTable对象来解析资源ID。解压相应的路径,从中获得相应的资源表,然后加入到其中。每一次的调用都会调用,appendPathToResTable,将新增的路径的资源表添加到其中。

根据ID获取TypedValue

void getValue(@AnyRes int id, TypedValue outValue, boolean resolveRefs)
throws NotFoundException {
boolean found = mAssets.getResourceValue(id, 0, outValue, resolveRefs);
if (found) {
return;
}
throw new NotFoundException(“Resource ID #0x” + Integer.toHexString(id));
}

final boolean getResourceValue(@AnyRes int resId, int densityDpi, @NonNull TypedValue outValue,
boolean resolveRefs) {
final int block = loadResourceValue(resId, (short) densityDpi, outValue, resolveRefs);
if (block < 0) {
return false;
}
if (outValue.type == TypedValue.TYPE_STRING) {
outValue.string = mStringBlocks[block].get(outValue.data);
}
return true;
}

从AssetManager中根据ID获取Value值。

static jint android_content_AssetManager_loadResourceValue(JNIEnv* env, jobject clazz,
jint ident,
jshort density,
jobject outValue,
jboolean resolve)
{
if (outValue == NULL) {
jniThrowNullPointerException(env, “outValue”);
return 0;
}
AssetManager* am = assetManagerForJavaObject(env, clazz);
if (am == NULL) {
return 0;
}
const ResTable& res(am->getResources());

Res_value value;
ResTable_config config;
uint32_t typeSpecFlags;
ssize_t block = res.getResource(ident, &value, false, density, &typeSpecFlags, &config);
if (kThrowOnBadId) {
if (block == BAD_INDEX) {
jniThrowException(env, “java/lang/IllegalStateException”, “Bad resource!”);
return 0;
}
}
uint32_t ref = ident;
if (resolve) {
block = res.resolveReference(&value, block, &ref, &typeSpecFlags, &config);
if (kThrowOnBadId) {
if (block == BAD_INDEX) {
jniThrowException(env, “java/lang/IllegalStateException”, “Bad resource!”);
return 0;
}
}
}
if (block >= 0) {
return copyValue(env, outValue, &res, value, ref, block, typeSpecFlags, &config);
}

return static_cast(block);
}

对于资源的TypedValue的获取核心代码。

const ResTable& res(am->getResources());
ssize_t block = res.getResource(ident, &value, false, density, &typeSpecFlags, &config);

const ResTable& AssetManager::getResources(bool required) const
{
const ResTable* rt = getResTable(required);
return *rt;
}

根据AssetManager中设置的资源路径来查找资源Table

首先判断是否已经存在ResTable,如果不存在则创建,存在则会直接返回。然后根据路径去查找相应的Resources文件,然后将其转化为ResTable,方便后面的查找。

const ResTable* AssetManager::getResTable(bool required) const
{
ResTable* rt = mResources;
//已经存在
if (rt) {
return rt;
}

AutoMutex _l(mLock);

if (mResources != NULL) {
return mResources;
}

if (mCacheMode != CACHE_OFF && !mCacheValid) {
const_cast<AssetManager*>(this)->loadFileNameCacheLocked();
}

//创建ResTable
mResources = new ResTable();
updateResourceParamsLocked();

bool onlyEmptyResources = true;
const size_t N = mAssetPaths.size();
//遍历Asset路径,对于路径调用appendPathToResTable
for (size_t i=0; i<N; i++) {
bool empty = appendPathToResTable(mAssetPaths.itemAt(i));
onlyEmptyResources = onlyEmptyResources && empty;
}

//如果为空,则证明没有找到resources.arsc文件
if (required && onlyEmptyResources) {
ALOGW(“Unable to find resources file resources.arsc”);
delete mResources;
mResources = NULL;
}

return mResources;
}

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());
}

通过mResourcesManager获得Resources对象,如果不存在,则创建一个。

小结

对于资源的加载,大概可以通过上图进行概括,根据ID获取TypedValue,TypedValue的获取是在AssetManager添加资源路径的时候,通过对资源表的解析来构建的一个ResTable,通过该数据结构根据ID作为索引查找并构建TypedValue,然后再根据资源文件的类型,借助TypedValue内存储的关于资源的详细信息来获取资源,同时将加载的资源进行缓存。因此在插件化的方案中,通过创建新的Resource对象,为其添加新的Asset路径,从而构建出一个新的ResTable,实现通过ID进行非宿主App资源的装载。

补充:一个AssetManager对应了一个ResTable,没为AssetTable设置一个资源路径之后,都会对资源路径进行解析,将其中的资源读出来,所有加载的资源都会放置到该表之中,因此我们就可以对其来获取TypeValue,根据TypeValue来进行相应的资源的查找了。

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数初中级Android工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则近万的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

img

img

img

img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

如果你觉得这些内容对你有帮助,可以扫码获取!!(备注:Android)

最后

只要是程序员,不管是Java还是Android,如果不去阅读源码,只看API文档,那就只是停留于皮毛,这对我们知识体系的建立和完备以及实战技术的提升都是不利的。

真正最能锻炼能力的便是直接去阅读源码,不仅限于阅读各大系统源码,还包括各种优秀的开源库。

腾讯、字节跳动、阿里、百度等BAT大厂 2019-2021面试真题解析

资料太多,全部展示会影响篇幅,暂时就先列举这些部分截图

《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》,点击传送门即可获取!

最后

只要是程序员,不管是Java还是Android,如果不去阅读源码,只看API文档,那就只是停留于皮毛,这对我们知识体系的建立和完备以及实战技术的提升都是不利的。

真正最能锻炼能力的便是直接去阅读源码,不仅限于阅读各大系统源码,还包括各种优秀的开源库。

[外链图片转存中…(img-YWjvYVcb-1712470864896)]

腾讯、字节跳动、阿里、百度等BAT大厂 2019-2021面试真题解析

[外链图片转存中…(img-jqO7L3ls-1712470864897)]

资料太多,全部展示会影响篇幅,暂时就先列举这些部分截图

《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》,点击传送门即可获取!
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值