編輯:關於 Android 開發
我們平常取得資源的起點是 getResources():
public Resources getResources() {
return mResources;
}
而 mResources 是在 ContextImpl 建立之後的初始化流程中產生的:
mResources = mPackageInfo.getResources(mainThread);
接著進入 LoadedApk 的 getResources:
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 與其他參數共同構成,其中最关键的就是 resDir——它標明了資源檔所在的路徑,也就是 APK 的實際位置。
這段邏輯的主軸是:先從 mActiveResources 這個 Map 中,以 ResourcesKey 為索引查找對應的 WeakReference<Resources>;找不到就建立,再放回 Map。
也就是說,只要這個 Map 裡存在多個指向不同路徑的 Resources 物件,我們就能同時存取多個來源的資源。這正是動態載入外部 APK 資源的立足點。
建立 Resources 的關鍵三步:
AssetManager assets = new AssetManager();
assets.setThemeSupport(compInfo.isThemeable);
if (assets.addAssetPath(resDir) == 0) {
return null;
}
r = new Resources(assets, dm, config, compInfo);
我們以前用 getAssets() 讀 assets 目錄時拿到的物件,其實就是在這裡被生出來的。AssetManager 的建構子:
public AssetManager() {
synchronized (this) {
init();
ensureSystemAssets();
}
}
init() 是 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"
// 因此 path 為 /system/framework/framework-res.apk
path.appendPath(kSystemAssets);
return addAssetPath(path, NULL);
}
所以 AssetManager 一誕生就已經裝了 framework 的資源,接著才透過 addAssetPath 掛上 App 自己的資源路徑:
/**
* 加入額外的資源來源,可以是目錄或 ZIP。
* @return 成功時回傳該資源的 cookie,失敗回傳 0
* @hide
*/
public native final int addAssetPath(String path);
同樣是 native,實作如下:
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;
bool res = am->addAssetPath(String8(path8.c_str()), &cookie);
return (res) ? (jint)cookie : 0;
}
到這裡就說得通了:Resources 內部的 AssetManager 同時包含 framework 與 App 自身的資源,這就是為什麼一個 getResources() 拿到的物件既能讀系統資源、也能讀本 App 資源。
答案是可以。既然 addAssetPath 能掛入任意路徑,那麼自建 AssetManager、掛上指定 APK、再用它開出 Resources,就能讀到別的 APK 裡的資源。換膚、換主題、動態資源包,背後都是這個思路。
唯一的障礙是 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 的 getResources 與 getAssets,讓整份程式碼的一致性更好:
@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 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,這裡取到的是自維護的 Resources
iv.setImageDrawable(getResources().getDrawable(0x7f020000));
break;
}
}
});
}
查一下可知插件事中那張 ic_launcher 的 id 是 0x7f020000:
public static final int ic_launcher = 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 ic_launcher = (int) getImageId.invoke(clazz);
iv.setImageDrawable(getResources().getDrawable(ic_launcher));
} catch (Exception e) {
e.printStackTrace();
}
}
讓每個插件事在 Manifest 裡宣告一個空的 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 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 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 btn = new Button(this);
btn.setText("風格" + (i + 1));
btn.setTag(i);
ll.addView(btn, new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int index = (Integer) btn.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 ic_launcher = (int) getImageId.invoke(clazz);
iv.setImageDrawable(getResources().getDrawable(ic_launcher));
} 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());
}
兩個插件事的結構各自為:
com.example.plugin
|-- Plugin.java
com.example.plugin2
|-- Plugin.java
Plugin 類別內容相同,作為提供宿主反射呼叫的入口;並在各自 Manifest 中註冊空 Activity:
<activity android:name=".plugin" android:label="@string/name">
<intent-filter>
<action android:name="android.intent.plugin" />
</intent-filter>
</activity>
這個技巧在換膚、按季節替換素材這類場景很好用,但正式專案仍要注意幾點:addAssetPath 屬性上是隱藏 API,不同 Android 版本有被收緊的可能;以固定 id 硬編碼的方式維護性極差,務必透過插件事提供的查詢函式取得;此外,動態載入外部 APK inherently 伴隨完整性與簽名校驗的問題,來源必須嚴格控管,否則等於替攻擊者開了一扇門。
用 Visual Studio 2015 開發 Android:環境搭建與踩坑記錄
近來一連串新聞——甲骨文向谷歌求償、傳出谷歌有意在 Android 上放棄 Java、甚至考慮引入 Swift 作為「一等」開發語言——讓我意識到跨平台開發能力的重要性。
Notification 進階用法:通知更新管理與自定義通知欄
Notification 進階用法:通知更新管理與自定義通知欄 示例一:通知欄的更新管理 當同一類事件頻繁發生時,作為開發者應該避免每來一條就推送一條全新通知,而是更新既
突破兩層限制:用 ExpandableListView 實現三級樹形菜單
Android 裡做樹形菜單,標準答案是 ExpandableListView(也有高手乾脆自己繼承 ListView 或 LinearLayout 手刻)。但它天生只支
ListView 自適應表格實作:讓每個單元格都能自訂尺寸
用 ListView 拼出一張會自適應的表格,是不少 Android 新手會卡住的地方。老實說,如果只講「自適應表格」,GridView 其實更好寫;但 GridView