Android再爱我一次(2)——加载其他app的资源

被xx跳动大佬使劲儿蹂躏了一把,赶紧回来总结总结

本文参考红橙大神的博客



iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_launcher_background));

一句话就能把图片资源加载完成,凭啥啊?

1. 翻源码

首先,src是通过TypedArray获取的,点开ImageView的源码直接找对象

final TypedArray a = context.obtainStyledAttributes(
                attrs, R.styleable.ImageView, defStyleAttr, defStyleRes);

        final Drawable d = a.getDrawable(R.styleable.ImageView_src);
        if (d != null) {
            setImageDrawable(d);
        }

有两个方法值得注意一下:

  1. getDrawable 返回Drawable对象
  2. setImageDrawable,这个方法是不是很眼熟
  @Nullable
    public Drawable getDrawableForDensity(@StyleableRes int index, int density) {
        if (mRecycled) {
            throw new RuntimeException("Cannot make calls to a recycled instance!");
        }
        final TypedValue value = mValue;
        if (getValueAt(index*AssetManager.STYLE_NUM_ENTRIES, value)) {
            if (value.type == TypedValue.TYPE_ATTRIBUTE) {
                throw new UnsupportedOperationException(
                        "Failed to resolve attribute at index " + index + ": " + value);
            }

            if (density > 0) {
                // If the density is overridden, the value in the TypedArray will not reflect this.
                // Do a separate lookup of the resourceId with the density override.
                mResources.getValueForDensity(value.resourceId, density, value, true);
            }
            return mResources.loadDrawable(value, value.resourceId, density, mTheme);
        }
        return null;
    }

本质还是调用了mResource里面的方法.

context中的处理

首先看Context关于getresource()方法 , 最终定位到这里

private Resources getResourcesInternal() {
        if (mResources == null) {
            if (mOverrideConfiguration == null) {
                mResources = super.getResources();
            } else {
                final Context resContext = createConfigurationContext(mOverrideConfiguration);
                mResources = resContext.getResources();
            }
        }
        return mResources;
    }

Resource的实例由Context 的子类创建,但是无法找到mBase的具体实例。 我们现在ContextImpl中找找。

private ContextImpl(ContextImpl container, ActivityThread mainThread,
            LoadedApk packageInfo, IBinder activityToken, UserHandle user, int flags,
            Display display, Configuration overrideConfiguration, int createDisplayWithId) {
       ......
       Resources resources = packageInfo.getResources(mainThread);

       if (resources != null) {
       // 不会走此分支,因为6.0中还不支持多屏显示,虽然已经有不少相关代码了,7.0以及正式支持多屏操作了
          if (displayId != Display.DEFAULT_DISPLAY
            || overrideConfiguration != null
            || (compatInfo != null && compatInfo.applicationScale
                    != resources.getCompatibilityInfo().applicationScale)) {
              ......
            }
       }
       ......
       mResources = resources;
}

// packageInfo.getResources 方法
public Resources getResources(ActivityThread mainThread) {
       // 缓存机制,如果LoadedApk中的mResources已经初始化则直接返回,
       // 否则通过ActivityThread创建resources对象
       if (mResources == null) {
           mResources = mainThread.getTopLevelResources(mResDir, mSplitResDirs, mOverlayDirs,
                   mApplicationInfo.sharedLibraryFiles, Display.DEFAULT_DISPLAY, this);
       }
       return mResources;
}

接下来跟到ResourceManager中

Resources getTopLevelResources(
            String resDir, //app资源文件夹路径,实际上是apk文件的路径,如/data/app/包名/base.apk
            String[] splitResDirs,//针对一个app由多个apk组成(将原本一个apk切片为若干apk)时,每个子apk中的资源文件夹
            String[] overlayDirs, 
            String[] libDirs, // app依赖的共享jar/apk路径
            int displayId,
            Configuration overrideConfiguration, CompatibilityInfo compatInfo) {
        final float scale = compatInfo.applicationScale;
        Configuration overrideConfigCopy = (overrideConfiguration != null)
                ? new Configuration(overrideConfiguration) : null;

      // 以apk路径为参数创建key
        ResourcesKey key = new ResourcesKey(resDir, displayId, overrideConfigCopy, scale);
        Resources r;
        synchronized (this) {
            // Resources is app scale dependent.
            if (DEBUG) Slog.w(TAG, "getTopLevelResources: " + resDir + " / " + scale);

            // 如果持有弱引用, 直接复用并返回
            WeakReference wr = mActiveResources.get(key);
            r = wr != null ? wr.get() : null;
          
            if (r != null && r.getAssets().isUpToDate()) {
                if (DEBUG) Slog.w(TAG, "Returning cached resources " + r + " " + resDir
                        + ": appScale=" + r.getCompatibilityInfo().applicationScale
                        + " key=" + key + " overrideConfig=" + overrideConfiguration);
                return r;
            }
        }

//使用apk的路径来初始化AssetsManager
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;
            }
        }
       
...
        // 没有弱引用,重新创建资源
        r = new Resources(assets, dm, config, compatInfo);
        if (DEBUG) Slog.i(TAG, "Created app resources " + resDir + " " + r + ": "
                + r.getConfiguration() + " appScale=" + r.getCompatibilityInfo().applicationScale);

        synchronized (this) {
            WeakReference wr = mActiveResources.get(key);
            Resources existing = wr != null ? wr.get() : null;
            if (existing != null && existing.getAssets().isUpToDate()) {
                r.getAssets().close();
                return existing;
            }
            // 将弱引用持有,缓存
            mActiveResources.put(key, new WeakReference<>(r));
            if (DEBUG) Slog.v(TAG, "mActiveResources.size()=" + mActiveResources.size());
            return r;
        }
    }

接下来不考虑缓存的情况 , 我们跟踪new Resource的情况

    public Resources(AssetManager assets, DisplayMetrics metrics, Configuration config,
        CompatibilityInfo compatInfo) {
    mAssets = assets;
    mMetrics.setToDefaults();
    if (compatInfo != null) {
        mCompatibilityInfo = compatInfo;
    }
    updateConfiguration(config, metrics);
    assets.ensureStringBlocks();
}
  1. packageInfo.getResources(mainThread)→
  2. mainThread.getTopLevelResources() →
  3. getTopLevelResources中, 已APK的路径作为key,首先查找是否存在弱引用,如不存在,直接创建Resource,创建过程必须要有AssetManager,DisplayMetrics,Configuration

AssetManager的创建是通过直接实例化对象调用了一个addAssetPath(path)方法把应用的apk路径添加到AssetManager,addAssetPath()方法请看源码解释。
创建好Resource之后会再去缓存中找Resource如果没有,那么则会创建Resource并将其缓存。 new Resources(assets, dm, config, compatInfo) 具体请看6.0源码240han。
至此,我们已经大致了解了Resource的查找过程。

3 Demo时间

在getTopLevelResources的方法中,传入了apk的路径,这个路径不止作为key来缓存Resource实例,而且是AssetsManager的初始化参数,进而将AssetsManager传入Resource的构造方法后,才完成了Resource的构造。那么,如果我们将其他akp的路径传进来,会不会就可以在我们的App里面使用其他apk的资源了?


需求: 点击按钮改变ImageView的显示图片, 且图片不在本App

首先,创建一个新的moudle, 只放入一张图片在drawable里 , 编译打包,名字随便改 我这里写test.apk

然后我们模拟Resource的创建方法

btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    //获取已创建好的Resource实例
                    Resources superResource = getResources();
                    //AssetsManager创建实例, 可以设置加载目标apk
                    AssetManager manager = AssetManager.class.newInstance();
                    //添加资源包
                    Method method = AssetManager.class.getDeclaredMethod("addAssetPath", String.class);

                    String skinPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "test.apk";
                    //反射执行方法
                    method.invoke(manager, skinPath);
                    Resources resources = new Resources(manager, superResource.getDisplayMetrics(), superResource.getConfiguration());
                    //第三个参数为包名
                    int drawableID2 = resources.getIdentifier("ic_test", "drawable", "ziye.skinplugin");
                    Drawable drawable = resources.getDrawable(drawableID2);

                    iv.setImageDrawable(drawable);

                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        });

AssetsManager都带有@hide标记,无法直接调用,这里用了反射


Android再爱我一次(2)——加载其他app的资源_第1张图片
image

你可能感兴趣的:(Android再爱我一次(2)——加载其他app的资源)