新技術真是層次不窮,八月份阿里做了件深的猿心的一件小事:dexposed 開源了。來看看 dexposed 是個啥?
What is it?
相信 Android 開發猿猿們都有過這個煩惱: Android 客戶端應用上線以後,難免會出現一些 bug ,特別是有些 bug 可能就只需要修改部分一兩句代碼的事,但是有不得不修復,然後發包。頻繁發包,對用戶,對開發來說的都是很蛋疼的體驗。所以優化的思路是在不發版本的情況下熱更新,以期提高用戶體驗。Dexposed 是一個強大的非侵入性 AOP 開源框架,針對 Android 開發的熱更新。這個框架是在另一個開源框架:Xposed的基礎上優化出來的。
如何使用?
- 引入依賴包:
dependencies { compile 'com.taobao.android:dexposed:0.1.1@aar' }
- 初始化並判斷你使用的版本能否使用(某些版本還在測試中)
public class MyApplication extends Application {
@Override public void onCreate() {
// Check whether current device is supported (also initialize Dexposed framework if not yet)
if (DexposedBridge.canDexposed(this)) {
// Use Dexposed to kick off AOP stuffs.
...
}
}
...
}
- 在patch工程中修復你的bug
你要修復的 bug 肯定是圍繞這某個類某個方法去修改的,所以這裏提供了三種方式:
1 在方法前插入邏輯 。
2 替換掉某個方法。
3 在某個方法之後插入邏輯。
例子1:下面這個例子演示如何在 Activity.onCreate(Bundle) 這個方法之前之後加入代碼片段:
//Target class, method with parameter types, followed by the hook callback (XC_MethodHook)
DexposedBridge.findAndHookMethod(Activity.class, "onCreate", Bundle.class, new XC_MethodHook() {
// To be invoked before Activity.onCreate().
@Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
// "thisObject" keeps the reference to the instance of target class.
Activity instance = (Activity) param.thisObject;
// The array args include all the parameters.
Bundle bundle = (Bundle) param.args[0];
Intent intent = new Intent();
// XposedHelpers provide useful utility methods.
XposedHelpers.setObjectField(param.thisObject, "mIntent", intent);
// Calling setResult() will bypass the original method body use the result as method return value directly.
if (bundle.containsKey("return"))
param.setResult(null);
}
// To be invoked after Activity.onCreate()
@Override protected void afterHookedMethod(MethodHookParam param) throws Throwable {
XposedHelpers.callMethod(param.thisObject, "sampleMethod", 2);
}
});
例子2:整個方法替換(我喜歡這種方式,乾淨利落)DexposedBridge.findAndHookMethod(Activity.class, "onCreate", Bundle.class, new XC_MethodReplacement() {
@Override protected Object replaceHookedMethod(MethodHookParam param) throws Throwable {
// Re-writing the method logic outside the original method context is a bit tricky but still viable.
...
}
});
- 支持的版本
Runtime | Android Version | Support |
---|---|---|
Dalvik | 2.2 | Not Test |
Dalvik | 2.3 | Yes |
Dalvik | 3.0 | No |
Dalvik | 4.0-4.4 | Yes |
ART | 5.0 | Testing |
ART | 5.1 | No |
ART | M | No |