編輯:關於 Android 程式設計
上一篇提到可以用 MultiDex 載入離線 APK,但那種做法有一個隱憂:APK 裡的類別全被併進當前的 PathClassLoader,插件一多,效能與 ANR 風險都跟著上來。
那能不能改用 DexClassLoader?當然可以。先看官方文件的定義:
A class loader that loads classes from .jar and .apk files containing a classes.dex entry. This can be used to execute code not installed as part of an application.
也就是說,DexClassLoader 能載入任何含有 classes.dex 的壓縮檔,jar 或 apk 都行——這正好就是我們要的「執行未安裝的程式碼」。
實作前先記住兩件事:
DexClassLoader(String dexPath, String optimizedDirectory, String libraryPath, ClassLoader parent)這個類別負責管理所有 DexClassLoader。我們先定義 BundleDexClassLoader 繼承自 DexClassLoader,每支離線 APK 對應一個實例;再用一個 List 保存它們,載入時逐一查找。
package net.mobctrl.hostapk;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public class BundleClassLoaderManager {
public static List<BundleDexClassLoader> bundleDexClassLoaderList
= new ArrayList<BundleDexClassLoader>();
/** 載入 Assets 裡的 apk 文件 */
public static void install(Context context) {
AssetsManager.copyAllAssetsApk(context);
// 取得 dex 文件列表
File dexDir = context.getDir(AssetsManager.APK_DIR, Context.MODE_PRIVATE);
File[] szFiles = dexDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
return filename.endsWith(AssetsManager.FILE_FILTER);
}
});
for (File f : szFiles) {
System.out.println("debug:load file:" + f.getName());
BundleDexClassLoader bundleDexClassLoader = new BundleDexClassLoader(
f.getAbsolutePath(),
dexDir.getAbsolutePath(),
null,
context.getClassLoader());
bundleDexClassLoaderList.add(bundleDexClassLoader);
}
}
/** 查找類別 */
public static Class<?> loadClass(Context context, String className)
throws ClassNotFoundException {
try {
Class<?> clazz = context.getClassLoader().loadClass(className);
if (clazz != null) {
System.out.println("debug: class find in main classLoader");
return clazz;
}
} catch (Exception e) {
e.printStackTrace();
}
for (BundleDexClassLoader bundleDexClassLoader : bundleDexClassLoaderList) {
try {
Class<?> clazz = bundleDexClassLoader.loadClass(className);
if (clazz != null) {
System.out.println("debug: class find in bundle classLoader");
return clazz;
}
} catch (Exception e) {
e.printStackTrace();
}
}
throw new ClassCastException(className + " not found exception");
}
}
兩個重點:
install():先把 assets 中的 APK 全部複製到私有目錄,再走訪該目錄,用 BundleDexClassLoader 逐個載入並存進清單。
loadClass():先往當前 ClassLoader 找,找不到再回頭走訪清單。
在 MainActivity 中透過反射呼叫插件類別的方法:
private void loadApk() {
try {
Class<?> clazz = BundleClassLoaderManager.loadClass(
getApplicationContext(), "net.mobctrl.normal.apk.Utils");
Constructor<?> constructor = clazz.getConstructor();
Object bundleUtils = constructor.newInstance();
Method printSumMethod = clazz.getMethod("printSum",
Context.class, int.class, int.class, String.class);
printSumMethod.setAccessible(true);
Integer sum = (Integer) printSumMethod.invoke(
bundleUtils, getApplicationContext(), 10, 20, "計算結果");
System.out.println("debug:sum = " + sum);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
與 MultiDex 方案最大的差異就在這裡:類別是透過 BundleClassLoaderManager 查找的,而不是依賴當前 ClassLoader。
仔細看 loadClass(),其實我們完全可以包一層自訂 ClassLoader,覆寫 findClass():先往當前 ClassLoader 找,找不到再走訪 BundleDexClassLoader。
mClassLoader = new ClassLoader(super.getClassLoader()) {
@Override
protected Class<?> findClass(String className) throws ClassNotFoundException {
Class<?> clazz = BundleClassLoaderManager.loadClass(context, className);
if (clazz == null) {
throw new ClassNotFoundException(className);
}
return clazz;
}
};
這樣做的好處是雙向可見:宿主能呼叫插件的類別,插件也能回頭引用宿主的類別,因為查找順序是「先自己、再插件」,而插件本身的 parent 又指向宿主 ClassLoader。
這篇與上一篇談的都是類別的載入。如果你要載入的目標全是工具類,不需要資源,那麼上面兩種方案都堪用。
但萬一載入的類別是 Fragment 或 Activity 這類 UI 元件,勢必要引用資源檔,又該怎麼辦?這就是下一篇要處理的題目。
告別制式圖標!手機端自訂APP圖標教學
想自訂APP圖標,需Root後用RE檔案管理器、X-plore與Photoshop手機版。先從APK的res/drawable-hdpi取出icon.png,編輯後存成P
Android ScrollView:如何偵測已經滑到底部
做「滑到底自動載入更多」的時候,第一個要解決的問題是:怎麼知道使用者已經滑到底了?做法是透過 OnTouchListener 攔截 ACTION_UP 事件,再比對 S
訊飛輸入法手寫靈敏度怎麼調?讓辨識速度跟上你的手
用手寫輸入時,常常會覺得反應慢半拍,字都寫完了才跳出候選字。這個問題多半可以靠調整「手寫靈敏度」改善。以下一步步說明設定位置。 步驟一:啟動訊飛輸入法 在手機介面找到訊
Android OkHttp 的 HTTP 攔截器 Interceptor 用法示例
OkHttp(GitHub:https://github.com/square/okhttp)的 Interceptor 正如其名「攔截器」,會攔截你的 Request