編輯:關於 Android 程式設計
換膚、主題切換、插件化資源的底層原理,其實都指向同一件事:能不能讓 App 在執行期讀到「另一個 APK」裡的資源。要回答這個問題,得先弄清楚系統原生的 Resources 是怎麼被建立起來的。
我們最熟悉的一句話是:
public Resources getResources() {
return mResources;
}
而 mResources 是在 ContextImpl 初始化時建立的:
mResources = mPackageInfo.getResources(mainThread);
跟進 LoadedApk:
public Resources getResources(ActivityThread mainThread) {
if (mResources == null) {
mResources = mainThread.getTopLevelResources(
mResDir, Display.DEFAULT_DISPLAY, null, this);
}
return mResources;
}
再走進 ActivityThread 的 getTopLevelResources()(省略部分日誌與註解):
Resources getTopLevelResources(String resDir, int displayId,
Configuration overrideConfiguration, CompatibilityInfo compInfo) {
ResourcesKey key = new ResourcesKey(resDir, displayId,
overrideConfiguration, compInfo.applicationScale,
compInfo.isThemeable);
Resources r;
synchronized (mPackages) {
WeakReference<Resources> wr = mActiveResources.get(key);
r = wr != null ? wr.get() : null;
if (r != null && r.getAssets().isUpToDate()) {
return r; // 命中快取,直接回傳
}
}
// 快取沒有,重新建立
AssetManager assets = new AssetManager();
assets.setThemeSupport(compInfo.isThemeable);
if (assets.addAssetPath(resDir) == 0) {
return null;
}
r = new Resources(assets, dm, config, compInfo);
synchronized (mPackages) {
WeakReference<Resources> 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<Resources>(r));
return r;
}
}
這段邏輯的重點有兩個。第一,ResourcesKey 主要由 resDir 決定,也就是 APK 檔案所在的路徑。第二,系統用一個 Map(mActiveResources)維護「ResourcesKey → 弱引用 Resources」的對應關係,命中就直接复用,沒命中才建立。
結論很關鍵:既然 Resources 的實例是以資源路徑為索引來快取的,那麼只要我們能給它一個不同的路徑,就能讀到另一份資源。
建立 Resources 的關鍵三行:
AssetManager assets = new AssetManager();
assets.setThemeSupport(compInfo.isThemeable);
if (assets.addAssetPath(resDir) == 0) {
return null;
}
r = new Resources(assets, dm, config, compInfo);
AssetManager 的建構子會呼叫 native 的 init():
public AssetManager() {
synchronized (this) {
if (DEBUG_REFS) {
mNumRefs = 0;
incRefsLocked(this.hashCode());
}
init();
ensureSystemAssets();
}
}
其 native 實作在 android_util_AssetManager.cpp:
static void android_content_AssetManager_init(JNIEnv* env, jobject clazz) {
AssetManager* am = new AssetManager();
if (am == NULL) {
jniThrowException(env, "java/lang/OutOfMemoryError", "");
return;
}
// 把 Framework 的資源加入 AssetManager 的搜尋路徑
am->addDefaultAssets();
env->SetIntField(clazz, gAssetManagerOffsets.mObject, (jint)am);
}
bool AssetManager::addDefaultAssets() {
// /system
const char* root = getenv("ANDROID_ROOT");
LOG_ALWAYS_FATAL_IF(root == NULL, "ANDROID_ROOT not set");
String8 path(root);
// kSystemAssets = "framework/framework-res.apk"
static const char* kSystemAssets = "framework/framework-res.apk";
path.appendPath(kSystemAssets);
return addAssetPath(path, NULL);
}
也就是說,AssetManager 一誕生就已經包含了 /system/framework/framework-res.apk,接著再加上本應用的資源路徑。這正好解釋了為什麼我們用 getResources() 拿到的物件,既能讀系統資源、也能讀自己的資源。
而 addAssetPath 同樣是 native 方法:
/** 加入額外的資源集,可以是目錄或 ZIP 檔。Not for use by applications. */
public native final int addAssetPath(String path);
static jint android_content_AssetManager_addAssetPath(
JNIEnv* env, jobject clazz, jstring path) {
ScopedUtfChars path8(env, path);
if (path8.c_str() == NULL) {
return 0;
}
AssetManager* am = assetManagerForJavaObject(env, clazz);
if (am == NULL) {
return 0;
}
void* cookie;
// 在 native 層完成資源路徑的加入
bool res = am->addAssetPath(String8(path8.c_str()), &cookie);
return (res) ? (jint)cookie : 0;
}
思路至此已經很清楚:自建一個 AssetManager,用 addAssetPath 塞入目標 APK 的路徑,再用它建構一個新的 Resources,之後所有資源讀取都走這個物件。唯一的障礙是 addAssetPath 被標記為 hide,用反射即可繞過。
public void loadRes(String path) {
try {
assetManager = AssetManager.class.newInstance();
Method addAssetPath = AssetManager.class.getMethod("addAssetPath", String.class);
addAssetPath.invoke(assetManager, path);
} catch (Exception e) {
e.printStackTrace();
}
resources = new Resources(assetManager,
super.getResources().getDisplayMetrics(),
super.getResources().getConfiguration());
}
其中 path 是目標 APK 的實際路徑,可以這樣取得:
getPackageManager().getApplicationInfo("xxx", 0).sourceDir;
接著覆寫 Context 的兩個方法,讓整份程式碼保持一致,呼叫端完全不需要改寫:
@Override
public Resources getResources() {
return resources == null ? super.getResources() : resources;
}
@Override
public AssetManager getAssets() {
return assetManager == null ? super.getAssets() : assetManager;
}
場景是這樣的:預設風格使用 App 自帶的資源;另一種風格則放在一個只包含資源的獨立插件 APK 中,切換時動態載入對應資源。


宿主程式碼:
private AssetManager assetManager;
private Resources resources;
private RadioGroup rg;
private ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.iv);
rg = (RadioGroup) findViewById(R.id.rg);
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.default_skin:
assetManager = null;
resources = null;
iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_launcher));
break;
case R.id.skin1:
String dexPath = "";
try {
dexPath = getPackageManager()
.getApplicationInfo("com.example.plugin", 0).sourceDir;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
loadRes(dexPath);
// 由於已覆寫 getResources(),這裡取到的是插件資源
iv.setImageDrawable(getResources().getDrawable(0x7f020000));
break;
}
}
});
}
這裡用 0x7f020000 硬編碼了資源 ID,僅是為了說明原理。實務上耦合這麼高很難維護,比較好的做法是讓插件提供一個取得 ID 的方法:
public class Plugin {
public static int getImageId() {
return R.drawable.ic_launcher;
}
}
宿主再用 DexClassLoader 反射呼叫:
private void setImage(String dexPath) {
DexClassLoader loader = new DexClassLoader(dexPath,
getApplicationInfo().dataDir, null,
this.getClass().getClassLoader());
try {
Class<?> clazz = loader.loadClass("com.example.plugin.Plugin");
Method getImageId = clazz.getMethod("getImageId");
int imageId = (int) getImageId.invoke(clazz);
iv.setImageDrawable(getResources().getDrawable(imageId));
} catch (Exception e) {
e.printStackTrace();
}
}
怎麼知道手機裡有哪些插件可用?一個常見做法是讓每個插件在 AndroidManifest.xml 中宣告一個空的 Activity,並掛上自訂的 action:
<activity android:name=".plugin">
<intent-filter>
<action android:name="android.intent.plugin" />
</intent-filter>
</activity>
宿主透過 PackageManager 就能把它們全部撈出來:
PackageManager pm = getPackageManager();
List<ResolveInfo> resolveinfos = pm.queryIntentActivities(intent, 0);
ActivityInfo activityInfo = resolveinfos.get(i).activityInfo;
dexPaths.add(activityInfo.applicationInfo.sourceDir);



完整的宿主實作:
private AssetManager assetManager;
private Resources resources;
private LinearLayout ll;
private ImageView iv;
private Button btn;
private final List<String> dexPaths = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.iv);
ll = (LinearLayout) findViewById(R.id.ll);
btn = (Button) findViewById(R.id.btn);
// 還原預設風格
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
resources = null;
iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_launcher));
}
});
Intent intent = new Intent("android.intent.plugin");
PackageManager pm = getPackageManager();
final List<ResolveInfo> resolveinfos = pm.queryIntentActivities(intent, 0);
for (int i = 0; i < resolveinfos.size(); i++) {
final ActivityInfo activityInfo = resolveinfos.get(i).activityInfo;
dexPaths.add(activityInfo.applicationInfo.sourceDir);
// 依插件數量動態產生按鈕
final Button skinBtn = new Button(this);
skinBtn.setText("風格" + (i + 1));
skinBtn.setTag(i);
ll.addView(skinBtn, new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
skinBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int index = (Integer) v.getTag();
loadRes(dexPaths.get(index));
setImage(resolveinfos.get(index).activityInfo);
}
});
}
}
private void setImage(ActivityInfo activityInfo) {
DexClassLoader loader = new DexClassLoader(
activityInfo.applicationInfo.sourceDir,
getApplicationInfo().dataDir, null,
this.getClass().getClassLoader());
try {
Class<?> clazz = loader.loadClass(activityInfo.packageName + ".Plugin");
Method getImageId = clazz.getMethod("getImageId");
int imageId = (int) getImageId.invoke(clazz);
iv.setImageDrawable(getResources().getDrawable(imageId));
} catch (Exception e) {
e.printStackTrace();
}
}
public void loadRes(String path) {
try {
assetManager = AssetManager.class.newInstance();
Method addAssetPath = AssetManager.class.getMethod("addAssetPath", String.class);
addAssetPath.invoke(assetManager, path);
} catch (Exception e) {
e.printStackTrace();
}
resources = new Resources(assetManager,
super.getResources().getDisplayMetrics(),
super.getResources().getConfiguration());
}
@Override
public Resources getResources() {
return resources == null ? super.getResources() : resources;
}
@Override
public AssetManager getAssets() {
return assetManager == null ? super.getAssets() : assetManager;
}
插件端結構非常簡單,com.example.plugin 與 com.example.plugin2 各自只有一個 Plugin.java(內容一致,供宿主反射呼叫),加上一份上面提過的空 Activity 宣告。
把原理講通之外,也該說清楚代價。資源 ID 在不同 APK 中並不保證一致,硬編碼 ID 或依賴對方回傳 ID 都很脆弱;此外 addAssetPath 是隱藏 API,跨版本升級時有失效風險;自建 Resources 也繞開了系統的資源快取管理。因此這套思路適合用來理解 Android 資源體系,或作為輕量換膚方案的參考;若要做完整的插件化,通常還需要一層資源 ID 重映射與相容性處理。
融雲進階玩法:自定義文件訊息,進而做出小影片、GIF 與紅包
先想清楚:這一切都是檔案傳輸 想在聊天裡發小影片?發 GIF?發紅包?發自定義表情?在融雲都能做。而這些看起來五花八門的功能,本質上都是同一件事——傳檔案,副檔名不外乎
動手實作 Android TreeView:用 ListView 拼出多層樹狀目錄
多數作業系統都提供了 TreeView 控制項來呈現樹狀結構,但 Google 在設計 Android 時考量到手機以觸控為主、手指點選層層展開的節點並不順手,因此只提供
Jenkins 持續整合 Android 項目(四):動手建立第一個 job
前面已經把系統相關設定都處理完了,接下來就可以正式建立專案。 建立新 job 選擇「新增項目」→「建立一個自由風格的軟體專案」,填入專案名稱即可。 注意:專案名稱不要
Android RadioGroup 單選按鈕使用詳解
先看效果單選按鈕是表單與設定頁面中常見的元件。Android 通常以 RadioGroup 搭配多個 RadioButton 來實作,讓同一群組中的選項只能有一個被選取。