项目配置
在AndroidMainfest.xml中添加
<meta-dataandroid:name="xposedmodule"android:value="true" /><meta-dataandroid:name="xposeddescription"android:value="Xposed模块初体验" /><meta-dataandroid:name="xposedminversion"android:value="53" />
在app/build.gradle中添加
compileOnly 'de.robv.android.xposed:api:82'compileOnly 'de.robv.android.xposed:api:82:sources'
在settings.gradle中添加
maven { url "https://api.xposed.info/" }
拖放一个button控件
MainActivity.java增加代码如下
private Button btn;
....
Button btn = (Button) findViewById(R.id.button);btn.setOnClickListener(new View.OnClickListener() {public void onClick(View v) {Toast.makeText(MainActivity.this, toastMessage(), Toast.LENGTH_SHORT).show();}});}public String toastMessage() {return "我未被劫持";}
在MainActivity的同级路径下新建一个类“HookTest.java”,代码如下:
package com.example.xpose;
import de.robv.android.xposed.IXposedHookLoadPackage;import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;import de.robv.android.xposed.XposedHelpers;import de.robv.android.xposed.callbacks.XC_LoadPackage;public class HookTest implements IXposedHookLoadPackage {public void handleLoadPackage(XC_LoadPackage.LoadPackageParam loadPackageParam) throws Throwable {if (loadPackageParam.packageName.equals("com.example.xpose")) {XposedBridge.log(" has Hooked!");Class clazz = loadPackageParam.classLoader.loadClass("com.example.xpose.MainActivity");XposedHelpers.findAndHookMethod(clazz, "toastMessage", new XC_MethodHook() {protected void beforeHookedMethod(MethodHookParam param) throws Throwable {super.beforeHookedMethod(param);//XposedBridge.log(" has Hooked!");}protected void afterHookedMethod(MethodHookParam param) throws Throwable {param.setResult("你已被劫持");}});}}}
无需理会报错:Cannot resolve symbol IXposedHookLoadPackage
基本上确定是Android Studio的bug
代码中“com.example.xpose”是目标程序的包名,“com.example.xpose.MainActivity” 是想要Hook的类, "toastMessage"是想要Hook的方法。我们在afterHookedMethod方法(用来定义Hook了目标方法之后的操作)中,修改了toastMessage()方法的返回值为“你已被劫持”。
右键点击 “main ” 文件夹 , 选择new --> Folder -->Assets Folder,新建assets 文件夹:
然后右键点击 assets文件夹, new–> file,文件名为xposed_init(文件类型选text),并在其中写上入口类的完整路径(就是自己编写的那一个Hook类),这样, Xposed框架就能够从这个 xposed_init 读取信息来找到模块的入口,然后进行Hook操作了。
成功劫持button消息