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

主目录见:Android高级进阶知识(这是总目录索引)

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

一.目标

今天的文章内容是为了插件化框架讲解做准备的知识的,我们的今天要达到的目标是:
1.能明白AssetManager是怎么加载资源的,apk内部或者外部的;
2.同时加深一下对资源的认识。

二.AssetManager

 前面我们已经知道因为ActivityContextWrapperContextImpl的关系,这个部分用的是装饰模式来实现的,所以在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;
....
}

这里的packageInfoLoadedApk对象,LoadedApk描述的是当前apk的一些信息,我们看到这个方法首先是调用了LoadedApk#getResources方法,传进去的参数是mainThreadmainThread对应的是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<Resources> 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方法来加载我们自己的资源文件。这个地方到时会详细讲解,现在只要有个意识就可以。

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容