Android AssetManager

Android AssetManager的创建

本文基于Android 6.0源码分析

AssetManager的类图

我们以一个"Hello World" APK(包名:com.jackyperf.assetmanagerdemo)为例。


  • ContextImpl:为Activity以及其他应用组件提供基础上下文,常用的Context API的实现
    都在这里

    • mPackageInfo:ContextImpl关联的组件所在Package信息
    • mResourcesManager:单列对象,管理应用内部多个Resources包
  • LoadedApk:管理一个加载的apk包

    • mResources:apk包对应的Resources对象
    • mResDir:资源存放路径/data/app/com.jackyperf.assetmanagerdemo-1/base.apk
  • ResourcesManager

    • mActiveResources:应用使用的Resources包的缓存
  • Resources:提供高级别的访问应用的资源的API

    • mSystem:系统Resources对象
    • mAssets:AssetManager对象
  • AssetManager:提供低级别的访问应用资源的API

    • sSystem:系统AssetMananger对象
    • mObject:指向Native层AssetManager
  • AssetManager(Native层)

    Every application that uses assets needs one instance of this. A
    single instance may be shared across multiple threads, and a single
    thread may have more than one instance
    (the latter is discouraged).

    The purpose of the AssetManager is to create Asset objects. To do
    this efficiently it may cache information about the locations of
    files it has seen.
    This can be controlled with the "cacheMode"
    argument.

    The asset hierarchy may be examined like a filesystem, using
    AssetDir objects to peruse a single directory.

    • mAssetPath:
    • mResources:代表APK中的资源表
    • mConfig:

AssetManager的创建流程


我们从ActivityThread的performLaunchActivity开始分析。

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    ...
    java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
    activity = mInstrumentation.newActivity(
            cl, component.getClassName(), r.intent);
    ...
    Application app = r.packageInfo.makeApplication(false, mInstrumentation);
    ...
    Context appContext = createBaseContextForActivity(r, activity, r.displayId);
    ...
}

代码位于/android/frameworks/base/core/java/android/app/ActivityThread.java

  • 在performLaunchActivity中首先通过反射创建Activity对象
  • 调用LoadedApk对象的makeApplication(),获取Activity所属应用的Application对象
  • 为Activity创建Base Context也就是ContextImpl对象,AssetManager对象就是
    在这里创建的。

接下来,我们分析createBaseContextForActivity()的实现。

private Context createBaseContextForActivity(ActivityClientRecord r,
        final Activity activity, int activityDisplayId) {
    ...
    ContextImpl appContext = ContextImpl.createActivityContext(
            this, r.packageInfo, displayId, r.overrideConfig/* { Multi-Window */, r.token/* Multi-Window } */);
    appContext.setOuterContext(activity);
    ...
}

代码位于/android/frameworks/base/core/java/android/app/ActivityThread.java

  • 调用ContextImpl的静态方法createActivityContext()创建ContextImpl对象,然后将Activity
    保存到ContextImpl的mOuterContext中。

createActivityContext()的实现计较简单,就是调用ContextImpl的构造函数,在
ContextImpl的构造函数函数中会调用LoadedApk对象的getResouces()创建Resources对象,注意LoadedApk有
两个构造函数,一个用于系统包,一个用于普通的应用包
。在getResources()中最终调用ResourcesManager的getTopLevelResources()

接下来分析ResourcesManager的getTopLevelResources()。

private final ArrayMap<ResourcesKey, WeakReference<Resources> > mActiveResources =
        new ArrayMap<>();
...        
/**
 * Creates the top level Resources for applications with the given compatibility info.
 *
 * @param resDir the resource directory.
 * @param splitResDirs split resource directories.
 * @param overlayDirs the resource overlay directories.
 * @param libDirs the shared library resource dirs this app references.
 * @param displayId display Id.
 * @param overrideConfiguration override configurations.
 * @param compatInfo the compatibility info. Must not be null.
 */
Resources getTopLevelResources(String resDir, String[] splitResDirs,
        String[] overlayDirs, String[] libDirs, int displayId,
        Configuration overrideConfiguration, CompatibilityInfo compatInfo) {
    ...
    ResourcesKey key = new ResourcesKey(resDir, displayId, overrideConfigCopy, scale);
    Resources r;
    synchronized (this) {
        // Resources is app scale dependent.
        if (DEBUG) Slog.w(TAG, "getTopLevelResources: " + resDir + " / " + scale);

        WeakReference<Resources> wr = mActiveResources.get(key);
        r = wr != null ? wr.get() : null;
        //if (r != null) Log.i(TAG, "isUpToDate " + resDir + ": " + r.getAssets().isUpToDate());
        if (r != null && r.getAssets().isUpToDate()) {
        if (DEBUG) Slog.w(TAG, "Returning cached resources " + r + " " + resDir
                + ": appScale=" + r.getCompatibilityInfo().applicationScale
                + " key=" + key + " overrideConfig=" + overrideConfiguration);
             return r;
         }
     }
     ...
     AssetManager assets = new AssetManager();
     if (resDir != null) {
         if (assets.addAssetPath(resDir) == 0) {
             return null;
         }
     }
     ...
     r = new Resources(assets, dm, config, compatInfo);
     ...
     synchronized (this) {
        WeakReference<Resources> wr = mActiveResources.get(key);
        Resources existing = wr != null ? wr.get() : null;
        if (existing != null && existing.getAssets().isUpToDate()) {
            r.getAssets().close();
            return existing;
        }

        mActiveResources.put(key, new WeakReference<>(r));
        return r;
     }
}

代码位于/frameworks/base/core/java/android/app/ResourcesManager.java

  • mActiveResources是一个ArrayMap用于存放应用内部ResourcesKey到Resources的映射,ResoucesKey实际上是
    资源路径、应用缩放、userId等信息封装的key。
  • 首先根据应用资源路径、缩放、userId等信息创建ResourcesKey,在mActiveResources中查找对应的Resources对象
    如果已经创建,并且Resources内部AssetManager的状态与资源文件一致,直接返回。
  • 否则,重建AssetManager对象,将应用资源路径添加AssetManager
  • 利用新的AssetManager、配置、兼容信息创建Resources对象
  • 最后将新创建的Resources对象以及ResourcesKey保存到mActiveResources,此时要考虑
    并发的问题,如果在locked之前已经有其他线程创建好了Resources对象,并且状态是最新的,直接
    返回已有的Resources对象。

下面重点分析AssetManager以及Resources的构造函数,先看AssetManager的构造函数。

public AssetManager() {
    synchronized (this) {
        ...
        init(false);
        ensureSystemAssets();
    }
}
  • 调用native方法init()来创建并初始化Native层的AssetManager对象。
  • 调用ensureSystemAssets()来确保系统资源管理对象已经创建并初始化。

应用内部应该使用Resources的getAssets()获取AssetManager对象。

下面分析Native层的AssetManager的创建以及初始化。

static void android_content_AssetManager_init(JNIEnv* env, jobject clazz, jboolean isSystem)
{
    ...
    AssetManager* am = new AssetManager();
    ...
    am->addDefaultAssets();
    env->SetLongField(clazz, gAssetManagerOffsets.mObject, reinterpret_cast<jlong>(am));
}

代码位于/frameworks/base/core/jni/android_util_AssetManager.cpp

  • 在android_content_AssetManager_init()中首先创建Native层AssetManager对象
  • 调用AssetManager对象的addDefaultAssets添加系统资源
  • 最后将Native层的AssetManager对象地址保存在相应的Java对象的mObject中

下面分析addDefaultAssets()的实现。

bool AssetManager::addDefaultAssets()
{
    const char* root = getenv("ANDROID_ROOT");

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

    return addAssetPath(path, NULL);
}

bool AssetManager::addAssetPath(const String8& path, int32_t* cookie)
{
    ...
    asset_path ap;
    ...
    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;
        }
    }
    ...
    mAssetPaths.add(ap);

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

    return true;
}
  • 在addDefaultAssets()中首先创建系统资源路径,一般ANDROID_ROOT环境变量为"/system",kSystemAssets为
    "framework/framework-res.apk",所以系统资源路径为"/system/framework/framework-res.apk"。然后调用addAssetPath()。
  • 在addAssetPath()中,首先检查mAssetPaths中是否已经包含了当前资源路径对应的asset_path对象,如果已经存在,返回asset_path在
    mAssetPaths中的索引值+1,所以*cookie的值从1开始。
  • 否则,将asset_path添加到mAssetPaths中,同时给*cookie赋值。
  • 如果资源表不为NULL,将asset_path添加到资源表。

最后我们再来分析下Resources的构造函数。

public Resources(AssetManager assets, DisplayMetrics metrics, Configuration config,
        CompatibilityInfo compatInfo) {
    mAssets = assets;
    ...
    updateConfiguration(config, metrics);
    assets.ensureStringBlocks();
}
  • 在Reosurces的构造函数中,首先将之前创建的AssetManager对象保存到mAssets中。
  • 调用updateConfiguration()更新设备配置信息,如设备屏幕信息、国家地区网络信息以及键盘配置信息等,最终会将这些信息
    保存到Native层的AssetManager对象中去。
  • 调用ensureStringBlocks将系统资源表以及应用资源表中的字符串资源池地址保存到AssetManager的mStringBlocks中。

参考

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

推荐阅读更多精彩内容