新技术真是层次不穷,八月份阿里做了件深的猿心的一件小事: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 |