继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Android DEXPOSED热更新

当年话下
关注TA
已关注
手记 124
粉丝 14
获赞 50

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

        });


  • 支持的版本

RuntimeAndroid VersionSupport
Dalvik2.2Not Test
Dalvik2.3Yes
Dalvik3.0No
Dalvik4.0-4.4Yes
ART5.0Testing
ART5.1No
ARTMNo

原文链接:http://www.apkbus.com/blog-705730-61657.html

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP