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

之前一段时间项目比较忙所以一直没有更新,接下来准备把插件化系列的文章写完,今天我们就先跳过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方法来加载我们自己的资源文件。这个地方到时会详细讲解,现在只要有个意识就可以。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值