写在文头
App-Bundle子2018的google IO大会面世已经一年多了,国内相关资料却大都是官方文档直译过来,鲜有真实案例,以及一些易错点的介绍,因此这里我将列举自己的一些采坑合集。
简单介绍
App Bundle基本框架看图说话:上图是直接从google官网挪过来的,从图中不难App Bunlde主要由以下几个模块构成
- base-moudle:包含应用的基本信息,如是否混淆,版本号等
- config.pb:该文件用来为google的库提供必要的数据来保证bundle的功能
- dynamic module:是一个个单独的功能模块,该模块中的resource和so库等又会如同上图左侧BaseModule一样去拆分
详情可转至:https://developer.android.com/guide/app-bundle/playcore
如何使用
App bundle的入门总体而言较为简单,官方有详尽的教程:飞机票
这里简单介绍一下几个要点:
- 使用AS开发App bundle的应用时,AS的版本需要>=3.2
- 在Application中调用如下方法:
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
SplitCompat.install(this);
}
- 在Activity中调用如下方法:
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
SplitCompat.installActivity(this);
}
- 如果dynamic的包>10M,需要在监听器中调用bundle支持库中的方法去确认是否下载
- Dynamic中的so库的加载方式需要替换成
SplitInstallHelper.loadLibrary(Context ctx, String name))
- dynamic中的资源不能跟base.apk同名,IDE会在编译器给出提示
踩坑实录
- Activity横竖屏切换后,出现找不到资源的问题
- dynamic module中有webview时,加载后出现找不到资源的问题
需要知道的是,通过Context去get资源时,都是通过Context的Resource里面的AssetManager去寻得相应的资源。既然在切屏和初始化webview后找不到资源,于是笔者在相应的位置输出了当前AssetManager的地址,结果是地址变了!!!于是在相应位置调用SplitCompat.installActivity(ctx)完美解决问题。
不妨看下SplitCompat.install的源码:
由于是混淆代码,这里只列出了关键的方法
private static void a(Context var0, Set<File> var1) {
AssetManager var2 = var0.getAssets();
Iterator var3 = var1.iterator();
while(var3.hasNext()) {
File var4 = (File)var3.next();
int var5 = (Integer)az.a(var2, "addAssetPath", Integer.class, String.class, var4.getPath());
Log.d("SplitCompat", (new StringBuilder(39)).append("addAssetPath completed with ").append(var5).toString());
}
}
不难看出该方法会重新赋值一个AssetManager给context.而该AssetManager将会有相关的resource信息
结语
本文写的较为简单,仅以作为踩坑记录
网友评论