Java – Is there a condition for the xposed method to replace the replaceHookedMethod with the replaceHookedMethod conditional?

Is there a condition for the xposed method to replace the replaceHookedMethod with the replaceHookedMethod conditional?… here is a solution to the problem.

Is there a condition for the xposed method to replace the replaceHookedMethod with the replaceHookedMethod conditional?

I’m new to xposed development and I’m stuck :

I

hook a method, check something, and then I want to decide whether to use return true; Replace it or let it run. But I haven’t found the possibility of setting a condition for replaceHookedMethod(..)

yet

I know I can set the return value in afterHookedMethod or beforeHookedMethod, but that doesn’t stop 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 simply achieve what you want using XC_MethodHook and beforeHookedMethod(..)

If you call param.setResult(..) or param.setThrowable(..) in beforeHookedMethod, your original hooked method will not be executed(..)

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 checkedXC_MethodReplacement, which confirms the statement I made at the beginning of this answer. It extends the XC_methodHook internally 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);
        }
    }

So, if you want to replace a method, just check the condition in beforeHookedMethod and set the result.

Related Problems and Solutions