javaandroidxposed-frameworkxposed

Is there a condition for xposed method replacement replaceHookedMethod?


I'm quite new to xposed development and i'm stuck:

I hook a method, check some stuff, then i want to decide wheter i replace it with just return true; or let it run. But i haven't found a possibility to set a condition to replaceHookedMethod(..)

I know i can set the return value in afterHookedMethod or beforeHookedMethod, but that doesnt prevent the method from running.

Here is my short example:

private static boolean flag;

...

findAndHookMethod(Activity.class, "onKeyDown", int.class, KeyEvent.class, new XC_MethodHook() {
    @Override
    protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
        //check some stuff here and set flag = true or flag = false
    }

    protected Object replaceHookedMethod(MethodHookParam param) throws Throwable {
        //this methode should only be called if the flag is true
        return true;
    }
};

Any ideas / suggestions? Thanks in advance!


Solution

  • You can simple achieve what you want using XC_MethodHook and beforeHookedMethod(..):

    The original method you have hooked will not be executed if you call param.setResult(..) or param.setThrowable(..) in beforeHookedMethod(..).

    It's not too hard to guess that the are executed before/after the original method. You can use the "before" method to evaluate/manipulate the parameters of the method call (via param.args) and even prevent the call to the original method (sending your own result). https://github.com/rovo89/XposedBridge/wiki/Development-tutorial

    I checked the source code of XC_MethodReplacement and it confirms the statements I made at the beginning of this answer. Internally it extends XC_methodHook and uses the following implementation:

        protected final void beforeHookedMethod(MethodHookParam param) throws Throwable {
            try {
                Object result = replaceHookedMethod(param);
                param.setResult(result);
            } catch (Throwable t) {
                param.setThrowable(t);
            }
        }
    

    Therefore you can simply check the condition in beforeHookedMethod and set the result if you want to replace the method.