热修复框架 - 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>
       final Object value = field.get(currentActivityThread);
       for (Map.Entry> entry
                : ((Map>) 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 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> 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 mAssetPaths

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

你可能感兴趣的:(热修复框架 - TinkerApplication启动(三) - 加载资源补丁过程)