Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 開發提高系列(5):動態加載(下)——加載已安裝 APK 中的類與資源

編輯:Android 開發實例

前言

本篇是 Android 動態加載系列的下篇,主題是加載已安裝 APK 中的類和資源。

正文

一、目標

需特別注意,這裡被調用的 APK 在 Android 系統中必須是已經安裝過的。

上篇回顧:Android 應用開發提高系列(4)——動態加載(上)——加載未安裝 APK 中的類。

本篇要實現的,是從當前 APK 中調用另一個已安裝 APK 的字符串、顏色值、圖片、布局文件資源以及 Activity。

二、實現

2.1 被調用工程:基本沿用上一個工程,僅新增了被調用的字符串、圖片等資源,此處不再贅述,文末附有工程下載鏈接。

2.2 調用工程代碼:

 public class TestAActivity extends Activity {
    /** TestB包名 */
    private static final String PACKAGE_TEST_B = "com.nmbb.b";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        try {
            final Context ctxTestB = getTestBContext();
            Resources res = ctxTestB.getResources();
            // 獲取字符串string
            String hello = res.getString(getId(res, "string", "hello"));
            ((TextView) findViewById(R.id.testb_string)).setText(hello);

            // 獲取圖片Drawable
            Drawable drawable = res.getDrawable(getId(res, "drawable", "testb"));
            ((ImageView) findViewById(R.id.testb_drawable)).setImageDrawable(drawable);

            // 獲取顏色值
            int color = res.getColor(getId(res, "color", "white"));
            ((TextView) findViewById(R.id.testb_color)).setBackgroundColor(color);

            // 獲取布局文件
            View view = getView(ctxTestB, getId(res, "layout", "main"));
            LinearLayout layout = (LinearLayout) findViewById(R.id.testb_layout);
            layout.addView(view);

            // 啟動TestB Activity
            findViewById(R.id.testb_activity).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        @SuppressWarnings("rawtypes")
                        Class cls = ctxTestB.getClassLoader().loadClass("com.nmbb.TestBActivity");
                        startActivity(new Intent(ctxTestB, cls));
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    private int getId(Resources testb, String resType, String resName) {
        return testb.getIdentifier(resName, resType, PACKAGE_TEST_B);
    }

    public View getView(Context ctx, int id) {
        return ((LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(id, null);
    }

    private Context getTestBContext() throws NameNotFoundException {
        return createPackageContext(PACKAGE_TEST_B, Context.CONTEXT_IGNORE_SECURITY | Context.CONTEXT_INCLUDE_CODE);
    }
}

代碼要點說明:

基本原理是通過包名獲取被調用應用的 Context,再藉由 Context 取得相應的資源與類。

需要留意:

a) 網上不少文章直接通過當前工程的 R.id 去調用被調用工程的資源,這是錯誤的,即便暫時不報錯也只是巧合——因為 R 是自動生成的,兩個應用的 id 根本無法對應,所以必須借助 getIdentifier 來查找。

b) Context.CONTEXT_INCLUDE_CODE 一般無需添加,但如果 layout 中包含自定義控件,就得把它加上。注意不能在當前工程裡強行轉換取用這個自定義控件,因為它處於另一個 ClassLoader 中,無法轉換。

c) 獲取這些資源並不需要 shareUserId。

三、總結

與上篇相比,這種方式獲取資源更為便捷,但也存在一些限制:

3.1 被調用的 apk 必須已經安裝,一定程度上影響用戶體驗。

3.2 style 無法動態設置,即便能取到也不例外。

3.3 就目前的研究來看,若被調用工程使用了自定義控件,會受到較大限制,無法強制轉換使用(原因如前所述)。

3.4 由於一個工程裡混入了兩個 Context,容易引發混淆,取資源也相對繁瑣。這裡分享一個批量映射兩個 apk id 的技巧:可通過反射讀取兩個 apk 的 R 類,一次性拿到每個 id 與對應值,再按名稱一一匹配,這樣就不必手工傳入字符串了。

 @SuppressWarnings("rawtypes")
    private static HashMap<String, Integer> getR(Class cls) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        HashMap<String, Integer> result = new HashMap<String, Integer>();
        for (Class r : cls.getClasses()) {
            if (!r.getName().endsWith("styleable")) {
                Object owner = r.newInstance();
                for (Field field : r.getFields()) {
                    result.put(field.getName(), field.getInt(owner));
                }
            }
        }
        return result;
    }

四、下載

Test2012-4-19.zip

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