Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 換膚方案:把皮膚包成獨立 APK 當插件載入

編輯:關於 Android 程式設計

轉載請註明出處:IT_xiao小巫

這篇來分享一個 Android 換膚的 Demo。相關程式碼都整理在 GitHub 上,後續文章涉及的程式碼也會統一放在那邊管理。

思路

換膚通常要換什麼?背景色、文字色、圖片、版面都可能牽涉進去。

Android 有 Theme 與 Style:Theme 作用於整個 Activity,Style 作用於指定控件。如果只是少量替換,在 App 內部做就好;但如果要動態切換,甚至支援線下班下載,那麼更實際的做法是:

把 App 與 skin 拆開,將 skin 做成一個獨立 APK 作為插件提供給 App 使用,這樣就能線下班下載皮膚並動態套用。

第一步:做一個只裝資源的皮膚包

這個 Demo 建了一個純 res 的專案,只提供 colors.xml,定義背景與按鈕的顏色:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="day_btn_color">#E61ABD</color>
    <color name="day_background">#38F709</color>
    <color name="night_btn_color">#000000</color>
    <color name="night_background">#FFFFFF</color>
</resources>

裡面完全沒有邏輯程式碼,只有資源檔。匯出成 skin.apk,複製到目標專案的 assets 目錄。

因為這裡不涉及下載流程,所以直接放 assets;程式啟動時再把 apk 複製到 SD 卡。

第二步:皮膚包管理器

public class SkinPackageManager {

    private static SkinPackageManager mInstance;
    private Context mContext;

    /** 當前皮膚包名 */
    public String mPackageName;
    /** 皮膚資源 */
    public Resources mResources;

    public SkinPackageManager(Context mContext) {
        this.mContext = mContext;
    }

    public static SkinPackageManager getInstance(Context mContext) {
        if (mInstance == null) {
            mInstance = new SkinPackageManager(mContext);
        }
        return mInstance;
    }

    /** 把 assets 裡的 apk 複製到 SD 卡 */
    public boolean copyApkFromAssets(Context context, String filename, String path) {
        boolean copyIsFinish = false;
        try {
            InputStream is = context.getAssets().open(filename);
            File file = new File(path);
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            byte[] temp = new byte[1024];
            int i;
            while ((i = is.read(temp)) > 0) {
                fos.write(temp, 0, i);
            }
            fos.close();
            is.close();
            copyIsFinish = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return copyIsFinish;
    }

    /** 非同步載入皮膚資源 */
    public void loadSkinAsync(String dexPath, final loadSkinCallBack callback) {
        new AsyncTask<String, Void, Resources>() {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                if (callback != null) callback.startloadSkin();
            }

            @Override
            protected Resources doInBackground(String... params) {
                try {
                    if (params.length == 1) {
                        String dexPath_tmp = params[0];

                        PackageManager mpm = mContext.getPackageManager();
                        PackageInfo mInfo = mpm.getPackageArchiveInfo(
                                dexPath_tmp, PackageManager.GET_ACTIVITIES);
                        mPackageName = mInfo.packageName;

                        // 用反射呼叫隱藏方法 addAssetPath
                        AssetManager assetManager = AssetManager.class.newInstance();
                        Method addAssetPath = assetManager.getClass()
                                .getMethod("addAssetPath", String.class);
                        addAssetPath.invoke(assetManager, dexPath_tmp);

                        Resources superRes = mContext.getResources();
                        Resources skinResource = new Resources(assetManager,
                                superRes.getDisplayMetrics(), superRes.getConfiguration());

                        SkinConfig.getInstance(mContext).setSkinResourcePath(dexPath_tmp);
                        return skinResource;
                    }
                } catch (Exception e) {
                    return null;
                }
                return null;
            }

            @Override
            protected void onPostExecute(Resources result) {
                super.onPostExecute(result);
                mResources = result;
                if (callback != null) {
                    if (mResources != null) callback.loadSkinSuccess();
                    else callback.loadSkinFail();
                }
            }
        }.execute(dexPath);
    }

    public static interface loadSkinCallBack {
        void startloadSkin();
        void loadSkinSuccess();
        void loadSkinFail();
    }
}

關鍵在 loadSkinAsync():它透過反射呼叫 AssetManager 的隱藏方法 addAssetPath(),把 skin.apk 的路徑掛進 AssetManager,再用這個 AssetManager 建出一個新的 Resources 物件。這樣一來,我們就能讀到別的 APK 裡的資源。

第三步:在 Activity 裡套用

public class MainActivity extends Activity implements OnClickListener, ISkinUpdate {

    private static final String APK_NAME = "skin.apk";
    private static final String DEX_PATH = Environment
            .getExternalStorageDirectory().getAbsolutePath() + "/skin.apk";

    private Button dayButton;
    private Button nightButton;
    private TextView textView;
    private boolean nightModel = false;

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

        dayButton   = (Button) findViewById(R.id.btn_day);
        nightButton = (Button) findViewById(R.id.btn_night);
        textView    = (TextView) findViewById(R.id.text);

        // 先把 apk 從 assets 複製到 SD 卡
        SkinPackageManager.getInstance(this).copyApkFromAssets(this, APK_NAME, DEX_PATH);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (SkinPackageManager.getInstance(this).mResources != null) {
            updateTheme();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_day:
                nightModel = false;
                loadSkin();
                break;
            case R.id.btn_night:
                nightModel = true;
                loadSkin();
                break;
        }
    }

    private void loadSkin() {
        SkinPackageManager.getInstance(this).loadSkinAsync(DEX_PATH, new loadSkinCallBack() {
            @Override public void startloadSkin() { Log.d("xiaowu", "startloadSkin"); }

            @Override
            public void loadSkinSuccess() {
                Log.d("xiaowu", "loadSkinSuccess");
                updateTheme();
            }

            @Override public void loadSkinFail() { Log.d("xiaowu", "loadSkinFail"); }
        });
    }

    @Override
    public void updateTheme() {
        Resources mResource = SkinPackageManager.getInstance(this).mResources;

        if (nightModel) {
            int id1 = mResource.getIdentifier("night_btn_color", "color", "com.devilwwj.res");
            nightButton.setBackgroundColor(mResource.getColor(id1));
            int id2 = mResource.getIdentifier("night_background", "color", "com.devilwwj.res");
            nightButton.setTextColor(mResource.getColor(id2));
            textView.setTextColor(mResource.getColor(id2));
        } else {
            int id1 = mResource.getIdentifier("day_btn_color", "color", "com.devilwwj.res");
            dayButton.setBackgroundColor(mResource.getColor(id1));
            int id2 = mResource.getIdentifier("day_background", "color", "com.devilwwj.res");
            dayButton.setTextColor(mResource.getColor(id2));
            textView.setTextColor(mResource.getColor(id2));
        }
    }
}

這裡要注意的是:因為皮膚資源的 ID 在編譯期不存在於 App 內,所以只能用 getIdentifier(name, type, packageName) 以「名稱 + 類型 + 皮膚包名」動態反查 ID,再從皮膚的 Resources 取值。

另外建議把「目前是白天或夜間」存進 SharedPreferences,啟動時先讀出來套用,使用者就不必每次重選。

跑一遍流程

1. 匯出 res 專案的 apk
2. 複製到目標專案的 assets 目錄
3. 啟動 App 觀察換膚效果

這套方案的延展性很好:真要支援線上換膚,只要把 skin.apk 改成從伺服器下載並做完整性校驗即可,其餘邏輯完全不用動。缺點是 getIdentifier 是字串比對,效能不如直接 ID 參照,實作時可以考慮在首次載入時建立一份名稱到 ID 的快取對照表。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved