热修复框架 - TinkerApplication启动(三) - 加载资源补丁过程

代码:tinker 1.9.14.7

一、Tinker加载资源补丁

TinkerLoader.tryLoadPatchFilesInternal 会执行TinkerResourceLoader.loadTinkerResources,此处开始加载资源补丁

TinkerResourceLoader.java

/**
* Load tinker resources
*/
public static boolean loadTinkerResources(TinkerApplication application, String directory, Intent intentResult) {
    if (resPatchInfo == null || resPatchInfo.resArscMd5 == null) {
        return true;
   }
    String resourceString = directory + "/" + RESOURCE_PATH +  "/" + RESOURCE_FILE;
   File resourceFile = new File(resourceString);
   long start = System.currentTimeMillis();
   //校验资源补丁包 resources.apk 的 md5 值
   if (application.isTinkerLoadVerifyFlag()) {
        if (!SharePatchFileUtil.checkResourceArscMd5(resourceFile, resPatchInfo.resArscMd5)) {
            Log.e(TAG, "Failed to load resource file, path: " + resourceFile.getPath() + ", expect md5: " + resPatchInfo.resArscMd5);
           ShareIntentUtil.setIntentReturnCode(intentResult, ShareConstants.ERROR_LOAD_PATCH_VERSION_RESOURCE_MD5_MISMATCH);
           return false;
       }
        Log.i(TAG, "verify resource file:" + resourceFile.getPath() + " md5, use time: " + (System.currentTimeMillis() - start));
   }
    try {
        //加载资源
        TinkerResourcePatcher.monkeyPatchExistingResources(application, resourceString);
       Log.i(TAG, "monkeyPatchExistingResources resource file:" + resourceString + ", use time: " + (System.currentTimeMillis() - start));
   } catch (Throwable e) {
        Log.e(TAG, "install resources failed");
       //remove patch dex if resource is installed failed
       try {
       //如果资源补丁加载失败的话,会移除 dex 补丁,因为如果dex补丁代码中有引用到资源的话,会报错
            SystemClassLoaderAdder.uninstallPatchDex(application.getClassLoader());
       } catch (Throwable throwable) {
            Log.e(TAG, "uninstallPatchDex failed", e);
       }
        intentResult.putExtra(ShareIntentUtil.INTENT_PATCH_EXCEPTION, e);
       ShareIntentUtil.setIntentReturnCode(intentResult, ShareConstants.ERROR_LOAD_PATCH_VERSION_RESOURCE_LOAD_EXCEPTION);
       return false;
   }
    return true;
}

先校验资源resources.apk 的 md5 值,然后加载资源,加载失败会导致dex补丁也被移除。

TinkerResourcePatcher.java

public static void monkeyPatchExistingResources(Context context, String externalResourceFile) throws Throwable {
    if (externalResourceFile == null) {
        return;
   }
    final ApplicationInfo appInfo = context.getApplicationInfo();
   final Field[] packagesFields;
   //利用 packagesFiled 反射获取 LoadedApk 对象,<27外加resourcePackagesFiled
   if (Build.VERSION.SDK_INT < 27) {
        packagesFields = new Field[]{packagesFiled, resourcePackagesFiled};
   } else {
        packagesFields = new Field[]{packagesFiled};
   }
    for (Field field : packagesFields) {
        //value = Map<String, WeakReference<LoadedApk>>
       final Object value = field.get(currentActivityThread);
       for (Map.Entry<String, WeakReference<?>> entry
                : ((Map<String, WeakReference<?>>) value).entrySet()) {
            final Object loadedApk = entry.getValue().get();
           if (loadedApk == null) {
                continue;
           }
            //从 LoadedApk 对象中获取 mResDir 属性, 即资源文件路径
           final String resDirPath = (String) resDir.get(loadedApk);
           Log.i(TAG, "resDirPath :" + resDirPath);
           if (appInfo.sourceDir.equals(resDirPath)) {
                //将修复资源放入资源文件路径
               resDir.set(loadedApk, externalResourceFile);
           }
        }
    }
     //创建一个新的 AssetManager 实例,并把资源补丁apk加载进 AssetManager 中
   // Create a new AssetManager instance and point it to the resources installed under
   if (((Integer) addAssetPathMethod.invoke(newAssetManager, externalResourceFile)) == 0) {
        throw new IllegalStateException("Could not create new AssetManager");
   }
    // Add SharedLibraries to AssetManager for resolve system resources not found issue
   // This influence SharedLibrary Package ID
   if (shouldAddSharedLibraryAssets(appInfo)) {
        for (String sharedLibrary : appInfo.sharedLibraryFiles) {
            if (!sharedLibrary.endsWith(".apk")) {
                continue;
           }
            if (((Integer) addAssetPathAsSharedLibraryMethod.invoke(newAssetManager, sharedLibrary)) == 0) {
                throw new IllegalStateException("AssetManager add SharedLibrary Fail");
           }
            Log.i(TAG, "addAssetPathAsSharedLibrary " + sharedLibrary);
       }
    }
    // Kitkat needs this method call, Lollipop doesn't. However, it doesn't seem to cause any harm
   // in L, so we do it unconditionally.
   /// 创建出 AssetManager 后,调用 ensureStringBlocks 来确保资源的字符串索引创建出来
   if (stringBlocksField != null && ensureStringBlocksMethod != null) {
        stringBlocksField.set(newAssetManager, null);
       ensureStringBlocksMethod.invoke(newAssetManager);
   }
    for (WeakReference<Resources> wr : references) {
        final Resources resources = wr.get();
       if (resources == null) {
            continue;
       }
        // Set the AssetManager of the Resources instance to our brand new one
       try {
            //pre-N 把原来 resources 的 mAssets 属性替换成新的 AssetManager 对象
           assetsFiled.set(resources, newAssetManager);
       } catch (Throwable ignore) {
            // N之后 mAssets 属性被放在了 ResourcesImpl 中 所以需要先获取 ResourcesImpl 对象再进行替换
           final Object resourceImpl = resourcesImplFiled.get(resources);
           // for Huawei HwResourcesImpl
           final Field implAssets = findField(resourceImpl, "mAssets");
           implAssets.set(resourceImpl, newAssetManager);
       }
        //在 Resource 中会维护一个 mTypedArrayPool 资源池,来减少频繁访问 AssetManager ,所以需要去释放这个资源池,否则取到的都是缓存
       clearPreloadTypedArrayIssue(resources);
       // 最后调用 updateConfiguration 方法来确保资源更新了
       resources.updateConfiguration(resources.getConfiguration(), resources.getDisplayMetrics());
   }
    // Handle issues caused by WebView on Android N.
   // Issue: On Android N, if an activity contains a webview, when screen rotates
   // our resource patch may lost effects.
   // for 5.x/6.x, we found Couldn't expand RemoteView for StatusBarNotification Exception
   if (Build.VERSION.SDK_INT >= 24) {
        try {
            if (publicSourceDirField != null) {
                publicSourceDirField.set(context.getApplicationInfo(), externalResourceFile);
           }
        } catch (Throwable ignore) {
            // Ignored.
       }
    }
    if (!checkResUpdate(context)) {
        throw new TinkerRuntimeException(ShareConstants.CHECK_RES_INSTALL_FAIL);
   }
}

二、资源加载原理

2.1 apk资源相关内容

apk包中与资源相关的文件:

  • assets 存放不参与编译的原始文件资源
  • res 存放资源文件,所有文件都被映射到R文件,生成对应资源id。
  • resources.arsc 它记录了资源文件,资源文件位置(各个维度的路径)和资源 id 的映射关系等。

2.2 资源加载流程

资源加载是指apk内部assets,res目录下的资源,通过Resources来获取的过程。

类关系

获取流程:
Resource通过代理ResourceImpl来处理,ResourceImpl先尝试从缓存获取,没有缓存在通过AssetManager获取,AssetManager通过addAssetPath来加载apk资源,而具体实现是在native做的。

三、资源补丁修复原理

从前面分析的tinker加载资源补丁流程看主要做了两件事:

  • 替换LoadedApk对应的mResDir指向补丁包。
  • ResourcesImpl mAssets替换为新的AssetManager,并用新AssetManager调用其addAssetPath加载补丁包。

3.1替换LoadedApk对应的mResDir指向补丁包

LoadedApk是 APK文件信息封装对象。它在ActivityThread启动过程中被初始化,参与Apk加载过程。

ActivityThread.java
   final ArrayMap<String, WeakReference<LoadedApk>> mPackages = new ArrayMap<>();

ActivityThread对各包维护了一个map,key=packageName,value=LoadedApk

LoadedApk.java 
   mResDir 指向资源文件对应的apk路径

那么直接通过反射到map中拿到包名对应的LoadedApk,然后获取属性mResDir,执行补丁包路径。

3.2 ResourcesImpl mAssets替换为新的AssetManager,并用新AssetManager调用其addAssetPath加载补丁包。

低版本mAssets在Resources中,这里代码有兼容。

ResourcesImpl.java
   final AssetManager mAssets;

addAssetPath调用栈:

AssetManager.java
   .addAssetPath(patchApkPath)
      . addAssetPathInternal
              .addAssetPathNative
                    | jni           

               android_util_AssetManager.cpp::android_content_AssetManager_addAssetPath
                      AssetManager::addAssetPath

最终将资源路径存放在一个Vector集合中:Vector<asset_path> mAssetPaths

参考:
https://segmentfault.com/a/1190000014016431
https://www.pianshen.com/article/9605795546/

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