安卓皮肤包机制的原理

作者: 嘉伟咯 | 来源:发表于2017-08-01 02:23 被阅读207次

许多常见的应用都有换肤的功能,甚至支持用户自定义皮肤。如果将所有皮肤用到的资源都打包到apk里面不仅会使得apk的大小急剧上升,也会大大增加维护的难度。所以大部分的开发者都会选择将这些资源从apk中剥离出来放到其他地方。

一种常用的方案就是将使用到的字符串、图片等资源打包到一个皮肤apk中,这个皮肤apk中只包含资源,没有任何的代码。主apk在启动之后从这个皮肤apk中加载资源,从而减少主apk的大小,同时也将不同皮肤的资源分别放到不同项目中,提高可维护性。

获取皮肤apk的Resources

我们都知道安卓应用的资源是通过Resources去管理的,只要能获取到皮肤apk的Resources,那么就能够读取到皮肤apk中的资源文件。

方法一

第一种获取Resources的方式是通过皮肤apk的Context去获取:

private Resources getResourcesByContext(Context context, String skinApkPackage) {
        try {
            return context.createPackageContext(skinApkPackage, Context.CONTEXT_IGNORE_SECURITY)
                    .getResources();

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return null;
    }

这种方式很简单,但是却有一定的局限性。因为要使用这种方式去获取Resources,必须将皮肤apk也安装到系统。

方法二

第二种方法是通过获取皮肤apk的AssetManager,直接new一个Resources出来:

private Resources getResourcesByAssetManager(Context context, String skinApkPath) {
        try {
            Method method = AssetManager.class.getDeclaredMethod("addAssetPath", String.class);
            AssetManager assetManager = AssetManager.class.newInstance();
            method.invoke(assetManager, skinApkPath);

            return new Resources(
                    assetManager,
                    context.getResources().getDisplayMetrics(),
                    context.getResources().getConfiguration()
            );
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }

这种方向需要用到反射去调用AssetManager.addAssetPath,但是只需要将皮肤apk下载下来,并不需要安装也能读取到里面的资源。

加载资源

一般我们都是通过资源的id从Resources中加载资源的,但是当资源在其他apk里面的时候,我们没有办法直接通过R类知道资源的id,所以需要使用Resources的getIdentifier方法去获取id:

public int getIdentifier(String name, String defType, String defPackage) {
        return mResourcesImpl.getIdentifier(name, defType, defPackage);
    }

获取到id之后就能直接加载资源了:

public String getString(String name) {
        int id = mResources.getIdentifier(name, "string", SKIN_APK_PACKAGE);
        if (id == 0) {
            return null;
        }
        return mResources.getString(id);
    }


    public Drawable getDrawable(String name) {
        int id = mResources.getIdentifier(name, "drawable", SKIN_APK_PACKAGE);
        if (id == 0) {
            return null;
        }
        return mResources.getDrawable(id);
    }

Demo

这个demo很简单

首先新建一个皮肤应用项目,在皮肤应用项目中放入img.png和创建一个字符串:

<resources>
    <string name="app_name">Skin</string>
    <string name="label">hello world</string>
</resources>

然后创建一个主应用项目在MainActivity中从皮肤apk加载图片和字符串显示出来

public class MainActivity extends AppCompatActivity {
    private final static String SKIN_APK_PACKAGE = "demo.linjw.skin";
    private final static String SKIN_APK = "skin-debug.apk";

    private SkinHelper mSkinHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //需要将皮肤apk安装到系统
        mSkinHelper = new SkinHelper(this, SKIN_APK_PACKAGE);

        //需要将皮肤apk放到存储卡根目录
        //File skinApk = new File(Environment.getExternalStorageDirectory().getPath(), SKIN_APK);
        //mSkinHelper = new SkinHelper(this, SKIN_APK_PACKAGE, skinApk);

        TextView textView = (TextView) findViewById(R.id.textView);
        textView.setText(mSkinHelper.getString("label"));

        ImageView imageView = (ImageView) findViewById(R.id.imageView);
        imageView.setImageDrawable(mSkinHelper.getDrawable("img"));
    }
}

SkinHelper代码如下:

public class SkinHelper {
    private final Resources mResources;
    private final String mSkinApkPackage;

    public SkinHelper(Context context, String skinApkPackage) {
        mSkinApkPackage = skinApkPackage;
        mResources = getResourcesByContext(context, skinApkPackage);
    }

    public SkinHelper(Context context, String skinApkPackage, File skinApk) {
        mSkinApkPackage = skinApkPackage;
        mResources = getResourcesByAssetManager(context, skinApk.getPath());
    }

    /**
     * 使用Context.createPackageContext加载Resource
     *
     * @param context
     * @return
     */
    private Resources getResourcesByContext(Context context, String skinApkPackage) {
        try {
            return context.createPackageContext(skinApkPackage, Context.CONTEXT_IGNORE_SECURITY)
                    .getResources();

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 使用反射创建AssertManager加载Resource
     *
     * @param context
     * @return
     */
    private Resources getResourcesByAssetManager(Context context, String skinApkPath) {
        try {
            Method method = AssetManager.class.getDeclaredMethod("addAssetPath", String.class);
            AssetManager assetManager = AssetManager.class.newInstance();
            method.invoke(assetManager, skinApkPath);

            return new Resources(
                    assetManager,
                    context.getResources().getDisplayMetrics(),
                    context.getResources().getConfiguration()
            );
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getString(String name) {
        int id = mResources.getIdentifier(name, "string", mSkinApkPackage);
        if (id == 0) {
            return null;
        }
        return mResources.getString(id);
    }


    public Drawable getDrawable(String name) {
        int id = mResources.getIdentifier(name, "drawable", mSkinApkPackage);
        if (id == 0) {
            return null;
        }
        return mResources.getDrawable(id);
    }
}

效果如下:

image.jpeg

完整代码

完整代码可以在这里获取

相关文章

网友评论

  • GrayMonkey:喵~~
  • 星林的窗:第二种觉得有点奇怪,不是说不需要安装吗?为什么去拿已安装的路径
    嘉伟咯:已经修改了下代码,现在第二种直接从存储卡根目录读取皮肤apk。
    嘉伟咯: @星林的窗 这个是因为我写第一种方式的时候已经把皮肤安装到系统了,所以写第二种的时候就顺手用了它,事实上不用安装,直接将它放到存储卡上也是可以的。

本文标题:安卓皮肤包机制的原理

本文链接:https://www.haomeiwen.com/subject/qpmdlxtx.html