详解Android插件化开发-资源访问
动态加载技术(也叫插件化技术),当项目越来越庞大的时候,我们通过插件化开发不仅可以减轻应用的内存和CPU占用,还可以实现热插拔,即在不发布新版本的情况下更新某些模块。 
    通常我们把安卓资源文件制作成插件的形式,无外乎有一下几种:
zip、jar、dex、APK(未安装APK、安装APK)
对于用户来讲未安装的APK才是用户所需要的,不安装、不重启,无声无息的加载资源文件,这正是我们开发者追求的结果。 
    但是,开发中宿主程序调起未安装的插件apk,一个很大的问题就是资源如何访问,这些资源文件的ID都映射在gen文件夹下的R.Java中,而插件中凡是以R开头的资源都不能访问。究其原因是因为宿主程序中并没有插件的资源,所以通过R来加载插件的资源是行不通的,程序会抛出异常:无法找到某某id所对应的资源。 
    那么开发中该怎么办呢,今天我们来一起探讨一下插件化开发中资源文件访问的解决方案。 
    想必大家在开发中都写过类似代码,例如,在主程序访问字符串文件
this.getResources().getString(R.string.app_name);这里的this,其实就是Context,上下文对象。通常我们的的APK安装路径为:
/data/apk/packagename~1/base.apk
APK启动,Context通过类加载器加载完毕后,会去APK中加载资源文件。想必大家都知道,Activity的工作主要是通过ContextImpl来完成的, Activity中有一个叫mBase的成员变量,它的类型就是ContextImpl。注意到Context中有如下两个抽象方法,看起来是和资源有关的,实际上Context就是通过它们来获取资源的。这两个抽象方法的真正实现在ContextImpl中,也就是说,只要实现这两个方法,就可以解决资源问题了。
/** Return an AssetManager instance for your application's package. */
public abstract AssetManager getAssets();
/** Return a Resources instance for your application's package. */
public abstract Resources getResources();我们若是想使用这两个方法,需要实例化Context对象,通常我们可以根据APK中的包名完成Context对象的创建:
Context pluginContext = this.createPackageContext("com.castiel.demo",flags);但是这样做有个前提,必须要求初始化时加载的是自己APK,如果我们加载的是未安装的插件APK,这么做肯定就不可取了。为啥呢,看源码:
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;Resources在这里被赋值,我们再去代码中第一行的packageInfo,它来自LoadedApk类,其中的getResources方法如下:
public Resources getResources(ActivityThread mainThread) {
        if (mResources == null) {
            mResources = mainThread.getTopLevelResources(mResDir, mSplitResDirs, mOverlayDirs,
                    mApplicationInfo.sharedLibraryFiles, Display.DEFAULT_DISPLAY, null, this);
        }
        return mResources;
    }该方法采用单例模式,注意其中的getTopLevelResources()方法中的第一个参数mResDir,我们继续找其源头,在ActivityThread类中,发现了:
    /**
     * Creates the top level resources for the given package.
     */
    Resources getTopLevelResources(String resDir, String[] splitResDirs, String[] overlayDirs,
            String[] libDirs, int displayId, Configuration overrideConfiguration,
            LoadedApk pkgInfo) {
        return mResourcesManager.getTopLevelResources(resDir, splitResDirs, overlayDirs, libDirs,
                displayId, overrideConfiguration, pkgInfo.getCompatibilityInfo(), null);
    }重点看里面的resDir参数,我们再往上找源码,最终找到ResourcesManager类,找到getTopLevelResources()方法:
    /**
     * Creates the top level Resources for applications with the given compatibility info.
     *
     * @param resDir the resource directory.
     * @param overlayDirs the resource overlay directories.
     * @param libDirs the shared library resource dirs this app references.
     * @param compatInfo the compability info. Must not be null.
     * @param token the application token for determining stack bounds.
     */
    public Resources getTopLevelResources(String resDir, String[] splitResDirs,
            String[] overlayDirs, String[] libDirs, int displayId,
            Configuration overrideConfiguration, CompatibilityInfo compatInfo, IBinder token) {
        final float scale = compatInfo.applicationScale;
        ResourcesKey key = new ResourcesKey(resDir, displayId, overrideConfiguration, scale, token);
        Resources r;
        synchronized (this) {
            // Resources is app scale dependent.
            if (false) {
                Slog.w(TAG, "getTopLevelResources: " + resDir + " / " + scale);
            }
            WeakReference<Resources> wr = mActiveResources.get(key);
            r = wr != null ? wr.get() : null;
            //if (r != null) Slog.i(TAG, "isUpToDate " + resDir + ": " + r.getAssets().isUpToDate());
            if (r != null && r.getAssets().isUpToDate()) {
                if (false) {
                    Slog.w(TAG, "Returning cached resources " + r + " " + resDir
                            + ": appScale=" + r.getCompatibilityInfo().applicationScale);
                }
                return r;
            }
        }
        //if (r != null) {
        //    Slog.w(TAG, "Throwing away out-of-date resources!!!! "
        //            + r + " " + resDir);
        //}
        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 (assets.addAssetPath(libDir) == 0) {
                    Slog.w(TAG, "Asset path '" + libDir +
                            "' does not exist or contains no resources.");
                }
            }
        }
        //Slog.i(TAG, "Resource: key=" + key + ", display metrics=" + metrics);
        DisplayMetrics dm = getDisplayMetricsLocked(displayId);
        Configuration config;
        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);
            }
        } else {
            config = getConfiguration();
        }
        r = new Resources(assets, dm, config, compatInfo, token);
        if (false) {
            Slog.i(TAG, "Created app resources " + resDir + " " + r + ": "
                    + r.getConfiguration() + " appScale="
                    + r.getCompatibilityInfo().applicationScale);
        }
        synchronized (this) {
            WeakReference<Resources> wr = mActiveResources.get(key);
            Resources existing = wr != null ? wr.get() : null;
            if (existing != null && existing.getAssets().isUpToDate()) {
                // Someone else already created the resources while we were
                // unlocked; go ahead and use theirs.
                r.getAssets().close();
                return existing;
            }
            // XXX need to remove entries when weak references go away
            mActiveResources.put(key, new WeakReference<Resources>(r));
            return r;
        }
}该方法的注释中,明确指出@param resDir the resource directory,加载本地资源目录,加载自己的APK。
通过以上的分析,我们知道getResources()方法通过AssetManager加载自己的APK,那么我们要想加载未安装的插件APK,唯有自定义实现一个Resources类,专门用来加载未安装的APK。但是我试过了,直接重写不行,为啥,因为Android并没有提供Resource构造方法中的AssetManager的构造方法,我们看下源码:
    /**
     * Create a new Resources object on top of an existing set of assets in an
     * AssetManager.
     *
     * @param assets Previously created AssetManager.
     * @param metrics Current display metrics to consider when
     *                selecting/computing resource values.
     * @param config Desired device configuration to consider when
     *               selecting/computing resource values (optional).
     */
    public Resources(AssetManager assets, DisplayMetrics metrics, Configuration config) {
        this(assets, metrics, config, CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO);
    }接着再看一下Resource构造方法中的AssetManager参数源码
    /**
     * Create a new AssetManager containing only the basic system assets.
     * Applications will not generally use this method, instead retrieving the
     * appropriate asset manager with {@link Resources#getAssets}.    Not for
     * use by applications.
     * {@hide}
     */
    public AssetManager() {
        synchronized (this) {
            if (DEBUG_REFS) {
                mNumRefs = 0;
                incRefsLocked(this.hashCode());
            }
            init(false);
            if (localLOGV) Log.v(TAG, "New asset manager: " + this);
            ensureSystemAssets();
        }
    }注意注释中的{@hide},隐藏起来了,Android系统不让我们使用。既然不让我们直接使用,那我们可以采用反射的方式来拿到AssetManager。接下来我把自定义的实现类贴出来,给大家示例:
/**
 *
 * @ClassName: MyPluginResources
 * @Description: 自定义插件资源文件获取工具类
 * @author 猴子搬来的救兵http://blog.csdn.net/mynameishuangshuai
 * @version
 */
public class MyPluginResources extends Resources{
    public MyPluginResources(AssetManager assets, DisplayMetrics metrics, Configuration config) {
        super(assets, metrics, config);
    }
    /**
     * 自定义返回插件的资源文件的Resource方法
     * @param resources
     * @param assets
     * @return
     */
    public static MyPluginResources getPluginResources(Resources resources,AssetManager assets){
        MyPluginResources pluginResources = new MyPluginResources(assets, resources.getDisplayMetrics(), resources.getConfiguration());
        return pluginResources;
    } 
    //自己定义加载插件APK的AssetsManager
    public static AssetManager getPluginAssetsManager(File apkFile,Resources resources) throws ClassNotFoundException{
        // 由于系统没有提供AssetManager的实例化方法,因此我们使用反射
        Class<?> forName = Class.forName("android.content.res.AssetManager");
        Method[] declaredMethods = forName.getDeclaredMethods();
        for(Method method :declaredMethods){
            if(method.getName().equals("addAssetPath")){
                try {
                    AssetManager assetManager = AssetManager.class.newInstance();
                    // 调用addAssetPath方法,参数为我们插件APK的路径
                    method.invoke(assetManager, apkFile.getAbsolutePath());
                    return assetManager;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}这样,我们在项目中就可以使用我们自定义的AssetManager来获取未安装插件APK中的资源文件
AssetManager assetManager = PluginResources.getPluginAssetsManager(apkFile,
            this.getResources());参考:《Android开发艺术探索》
详解Android插件化开发-资源访问的更多相关文章
- Android 插件化开发(四):插件化实现方案
		在经过上面铺垫后,我们可以尝试整体实现一下插件化了.这里我们先介绍一下最简单的实现插件化的方案. 一.最简单的插件化实现方案 最简单的插件化实现方案,对四大组件都是适用的,技术面涉及如下: 1). 合 ... 
- Android插件化开发
		客户端开发给人的印象往往是小巧,快速奔跑.但随着产品的发展,目前产生了大量的门户型客户端.功能模块持续集成,开发人员迅速增长.不同的开发小组开发不同的功能模块,甚至还有其他客户端集成进入.能做到功能模 ... 
- Android插件化开发---执行未安装apk中的Service
		欢迎各位增加我的Android开发群[257053751] 假设你还不知道什么叫插件化开发.那么你应该先读一读之前写的这篇博客:Android插件化开发,初入殿堂 上一篇博客主要从总体角度分析了一下 ... 
- Android 插件化开发(一):Java 反射技术介绍
		写在前面:学习插件化开发推荐书籍<Android 插件化开发指南>,本系列博客所整理知识部分内容出自此书. 在之前的项目架构的博文中,我们提到了项目插件化架构,提到插件化架构不得不提的到J ... 
- 《Android插件化开发指南》面世
		本书在京东购买地址:https://item.jd.com/31178047689.html 本书Q群:389329264 (一)这是一本什么书 如果只把本书当作纯粹介绍Android插件化技术的书籍 ... 
- 【我的Android进阶之旅】Android插件化开发学习资料
		1.目前开源的插件开发框架大致有哪些? 1. 任玉刚 的 dynamic-load-apk Github 地址:https://github.com/singwhatiwanna/dynamic-lo ... 
- Android 插件化开发(二):加载外部Dex文件
		在学习Java反射的技术后,我们可以开始更深一步的探究插件化开发了.首先先讲一下Android App的打包流程,然后我们通过一个简单的例子 —— 实现插件化加载外部Dex来完成初级的插件化开发的探索 ... 
- Android插件化开发,初入殿堂
		好久没有写博客了,这次准备写写我这几天的研究成果--Android插件化开发框架CJFrameForAndroid. 好久没有写博客了,这次准备写写我这几天的研究成果--Android插件化开发框架C ... 
- Android 插件化 开发
		插件化知识详细分解及原理 之Binder机制https://blog.csdn.net/yulong0809/article/details/56841993 插件化知识详细分解及原理 之代理,hoo ... 
随机推荐
- Ajax的几种形式 和使用情况
			Ajax的几种形式: 1 $.get( "Login.ashx", {Name:name,Pwd:pwd,action:x}, function(data){这里用da ... 
- T_SQL 字符串函数
			字符串函数用于处理列中的数据值,通常属于字符型的数据类型. 1.ASCLL(character),将具体字符转换为相应的整数(ASCII)代码,结果为正数. 例:select ASCII('A'), ... 
- XRDP与VNC的关系(转载)
			XRDP与VNC的关系 如果仅仅安装XRDP协议.是不能在windows上使用远程桌面连接到Ubuntu. 还须要安装VNCServer才行. 所以,XRDP启动之后.系统会自己主动启动一个VNC会话 ... 
- [POI2011]MET-Meteors 整体二分_树状数组_卡常
			线段树肯定会 TLE 的,必须要用树状数组. Code: // luogu-judger-enable-o2 #include <cstdio> #include <algorith ... 
- bzoj 2287: 【POJ Challenge】消失之物 动态规划
			Code: #include<cstdio> #include<algorithm> #include<queue> #include<cstring> ... 
- 临时的js方法
			//楼层的js var scroChange; //楼层跳转 function FloorGo(domId){//传入目标的id clearInterval(scroChange); var scro ... 
- C++输入流
			输出流基本概念 输出流定义在头文件中.大部分程序都会包含头文件,这个头文件又包含了输入流和输出流头文件.头文件还声明了标准控制台输出流cout. 使用输出流的最简单的方法是使用<<运算 ... 
- ArcGIS api for javascript——地理处理任务-瓶中信
			描述 如果在海洋中丢下一个瓶子,本例使用颗粒追踪模型显示指定的天数后瓶子在的地方.首先,输入一个追踪瓶子的天数.然后单击按钮并在海洋里的任意地方画一个点来开始模型.几秒以后将看到一条线出现描述瓶子将去 ... 
- cocos2d-x 3.0正式版 vs2013配置
			cocos2d-x 3.0正式版与之前的版本号差异较大,曾经的教程非常多都不使用了. 1.从cocos2d-x官网http://www.cocos2d-x.org下载3.0版的压缩包,随便解压一个位置 ... 
- 算法导论————KMP
			[例题传送门:caioj1177] KMP模版:子串是否出现 [题意]有两个字符串SA和SB,SA是母串,SB是子串,问子串SB是否在母串SA中出现过.如果出现过输出第一次出现的起始位置和结束位置,否 ... 
