详解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 ...
随机推荐
- Java类和对象9
(1)创建一个叫做机动车的类:属性:车牌号(String),车速(int),载重量(double)功能:加速(车速自增).减速(车速自减).修改车牌号,查询车的载重量.编写两个构造方法:一个没有形参, ...
- 泪奔,配好了bioconductor环境
最近因为极度忙,没有写总结.今天补一下总结. 今天完成关静最后给的大project这个作业来说,结合自己的研究方向是个让我纠结一周多的事.好在找到了对应的研究内容. R的书目前还是很多的.R我一开始觉 ...
- Perceptron Learning Algorithm(python实现)
一.概论 对于给定的n维(两种类型)数据(训练集),找出一个n-1维的面,能够"尽可能"地按照数据类型分开.通过这个面,我们可以通过这个面对测试数据进行预测. 例如对于二维数据,要 ...
- codeforces 400 D Dima and Bacteria【并查集 Floyd】
题意:给出n个点,分别属于k个集合,判断每个集合里面的点的距离都为0,为0的话输出yes,并输出任意两个集合之间的最短路 这道题目有两个地方不会处理, 先是n个点,分别属于k个集合,该怎么记录下来这里 ...
- Example of working with a dump.
Let's say that you are looking at a crash dump, so following the first command from this page you do ...
- NodeJS学习笔记 (29)二进制解码-string_decoder(ok)
原文:https://github.com/chyingp/nodejs-learning-guide 自己过一遍: 模块简介 string_decoder模块用于将Buffer转成对应的字符串.使用 ...
- Linux学习-Ubuntu 18.04-安装图文教程
Ubuntu(友帮拓.优般图.乌班图)是一个以桌面应用为主的开源GNU/Linux操作系统,Ubuntu 是基于Debian GNU/Linux,支持x86.amd64(即x64)和ppc架构,由全球 ...
- Java基础学习总结(18)——网络编程
一.网络基础概念 首先理清一个概念:网络编程 != 网站编程,网络编程现在一般称为TCP/IP编程. 二.网络通信协议及接口 三.通信协议分层思想 四.参考模型 五.IP协议 每个人的电脑都有一个独一 ...
- ArcGIS api for javascript——查询,立刻打开信息窗口
描述 本例展示了当一个要素被查询时如何立刻打开一个InfoWindow.信息窗口能被用来将要素的属性格式化成用户易读的格式. 本例中,地图和查询任务都使用ESRI sample server上的服务K ...
- HTML5学习笔记简明版(11):新增的API
HTMLDocument上的扩展 HTML5在DOM Level 2 HTML上扩展了一些HTMLDocument的接口.这些接口在全部实现了Document接口的元素对象上进行了实现. HTML5在 ...