美文网首页
Android 项目中资源文件 -- AssetManager

Android 项目中资源文件 -- AssetManager

作者: __Witness | 来源:发表于2020-06-11 17:34 被阅读0次

在上一篇 Android 项目中资源文件 -- assets目录文件的访问 中,我们简单记录了一下 assets 目录的访问。

这一篇将会跟踪源码去看看AssetManager的创建流程,因为要走源码,相对比较枯燥无味,所以先放一张安静的图片,平静一下自己的内心,再开始开车上路。


上一篇中,已经说到了我们要获取到一个 AssetManager 实例的方法。

  • mActivity.getAssets();
  • mActivity.getResources().getAssets();
    我们都是通过 activity 实例对象直接或者间接的去获取 AssetManager 对象。那我们应该知道,不管是 getAssets() 或者 getResources() ,他们都是被定义在android.app.Context 类中的方法。

Context.java中源码:

public abstract AssetManager getAssets();

public abstract Resources getResources();

很明显,他们两个都是 abstract 修饰的抽象方法,那我们想知道他们的具体实现,那我们就得移步 ContextImpl.java 类了。

注意:ContextImpl 类和 ReceiverRestrictedContext 类是写在一个java文件里的,查找的时候注意一下

ContextImpl.java 中源码:

@Override
public AssetManager getAssets() { 
    return getResources().getAssets();
}

@Override
public Resources getResources() {
   return mResources;
}

意外的发现,其实 mActivity.getAssets() 的方式获取 AssetManager 的方式,也就是先去获取 Resources 对象,然后再去调用 Resources 对象实例的 getAssets() 方法返回 AssetManager 实例。 这样,就说明了 两种方式的源码流程其实是一样的

既然,他们都会是产生 Resources 实例,那么接下来就要看看 Resources 是哪来的。
ContextImpl.java 中源码:

       private ContextImpl(ContextImpl container, ActivityThread mainThread,
                        LoadedApk packageInfo, IBinder activityToken, UserHandle user, boolean restricted,
                        Display display, Configuration overrideConfiguration) {
        ...省略多余源码
        mResourcesManager = ResourcesManager.getInstance();
        ...
        Resources resources = packageInfo.getResources(mainThread);
        if (resources != null) {
            if (activityToken != null
                    || displayId != Display.DEFAULT_DISPLAY
                    || overrideConfiguration != null
                    || (compatInfo != null && compatInfo.applicationScale
                    != resources.getCompatibilityInfo().applicationScale)) {
                resources = mResourcesManager.getTopLevelResources(packageInfo.getResDir(),
                        packageInfo.getSplitResDirs(), packageInfo.getOverlayDirs(),
                        packageInfo.getApplicationInfo().sharedLibraryFiles, displayId,
                        overrideConfiguration, compatInfo, activityToken);
            }
        }
        mResources = resources;
        
    }

参数 packageInfo 指向的是一个 LoadedApk 对象,这个对象描述的是当前 APK。 用来访问资源的 Resources 对象是通过调用参数
packageInfo 的成员函数 getResources() 创建的。这个 Resources 对象创建完成之后,由于程序的其他设置可能改变,需要重新生成 Resource ,最终生成的对象,就会保存在 ContextImpl 类的成员变量 mResources 中。生成 Resources 的最终都会调用 ResourcesManager .java 类中的 getTopLevelResources () 方法。

ResourcesManager.java 中源码:

Resources getTopLevelResources(String resDir, String[] splitResDirs,
        String[] overlayDirs, String[] libDirs, int displayId,
        Configuration overrideConfiguration, CompatibilityInfo compatInfo) {
    final float scale = compatInfo.applicationScale;
    Configuration overrideConfigCopy = (overrideConfiguration != null)
            ? new Configuration(overrideConfiguration) : null;
    ResourcesKey key = new ResourcesKey(resDir, displayId, overrideConfigCopy, scale);
    Resources r;
    synchronized (this) {
    // 省略
    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 (resDir != null) {
        if (assets.addAssetPath(resDir) == 0) {
            return null;
        }
    }
    if (splitResDirs != null) {
        for (String splitResDir : splitResDirs) {
            if (assets.addAssetPath(splitResDir) == 0) {
                return null;
            }
        }
    }
    if (overlayDirs != null) {
        for (String idmapPath : overlayDirs) {
            assets.addOverlayPath(idmapPath);
        }
    }
    if (libDirs != null) {
        for (String libDir : libDirs) {
            if (libDir.endsWith(".apk")) {
                // Avoid opening files we know do not have resources,
                // like code-only .jar files.
                if (assets.addAssetPath(libDir) == 0) {
                }
            }
        }
    }

    //Log.i(TAG, "Resource: key=" + key + ", display metrics=" + metrics);
    DisplayMetrics dm = getDisplayMetricsLocked(displayId);
    Configuration config;
    final boolean isDefaultDisplay = (displayId == Display.DEFAULT_DISPLAY);
    final boolean hasOverrideConfig = key.hasOverrideConfiguration();
    if (!isDefaultDisplay || hasOverrideConfig) {
        config = new Configuration(getConfiguration());
        if (!isDefaultDisplay) {
            applyNonDefaultDisplayMetricsToConfigurationLocked(dm, config);
        }
        if (hasOverrideConfig) {
            config.updateFrom(key.mOverrideConfiguration);
            if (DEBUG) Slog.v(TAG, "Applied overrideConfig=" + key.mOverrideConfiguration);
        }
    } else {
        config = getConfiguration();
    }
    r = new Resources(assets, dm, config, compatInfo);
    // 省略
        return r;
    }
}

getTopLevelResources() 来获取一个 Resources 对象的时候,需要指定要获取的 Resources 对象所对应的 APK 文件的路径,这个 APK 文件路径就保存在 LoadedApk 类的成员变量 mResDir 中,这里还可能有其他资源路径,也可以添加。

这样就创建出了 Resources 实例对象了。

那么,有了 Resources 对象,我们直接调用 getAssets() 方法就可以获得 AssertManager 对象了。

下面看AssetManager类的构造函数和成员函数addAssetPath的实现,接着再看Resources类的构造函数的实现。

AssetManager .java 中源码:

public AssetManager() {
    synchronized (this) {
        if (DEBUG_REFS) {
            mNumRefs = 0;
            incRefsLocked(this.hashCode());
        }
        init(false);
        if (localLOGV) Log.v(TAG, "New asset manager: " + this);
        ensureSystemAssets();
    }
}

// init为一个本地方法
private native final void init(boolean isSystem);

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

AssetManager 类的构造函数是通过调用另外一个函数 init() 来执行工作的。 在初始化完成当前正在创建的 AssetManager 对象后, AssetManager 类的构造函数还会调用另外一个方法 ensureSystemAssets() 检查当前进程是否已经创建了一个用来访问系统资源的 AssetManager 对象。

如果检查到 AssetManager 对象没有创建的话,那么 AssetManager 类的 ensureSystemAssets() 函数就会创建并且初始化它,同时将它保存在 AssetManager 的 sSystem 静态成员变量中。注意:创建用来访问系统资源和应用程序资源的 AssetManager 对象的过程是一样的,区别只是它们所要访问的 APK 文件不一样而已

相关文章

网友评论

      本文标题:Android 项目中资源文件 -- AssetManager

      本文链接:https://www.haomeiwen.com/subject/czjbtktx.html