Search code examples
androidhookandroid-contextxposed

How to get Context through hooking in android


The background is :

  1. I'm using xposed framework to hook a third party app.
  2. When I hook method XXX, xposed gave me "ClassNotFound" error. I checked and found the method XXX is in a dex file and would be loaded by DexClassLoader on the run.
  3. To hook the method XXX, I need to change the default ClassLoader in xposed to DexClassLoader. To get a DexClassLoader instance, I need a Context instance of the third party app.
  4. Here comes the question: how to get the context instance?

I searched stackoverflow and found someone said you can hook the method in Activity or Receiver to retrieve their context. But I checked the Activity.class and found no method that return Context type value, and only one method has Context type parameter, the onCreateView(String name, Context context, AttributeSet attrs).

Is there any way to get the Context?


Solution

  • The answer from the poster below is more succinct:

    Context context = (Context) AndroidAppHelper.currentApplication();
    

    An alternative hack is to retrieve the current activity (which can be cast to Context) like this:

    Class<?> instrumentation = XposedHelpers.findClass(
                    "android.app.Instrumentation", lpparam.classLoader);
    
    XposedBridge.hookAllMethods(instrumentation, "newActivity", new XC_MethodHook() {
    
                    @Override
                    protected void afterHookedMethod(MethodHookParam param) throws Throwable {
    
                        mCurrentActivity = (Activity) param.getResult();
    
                        Log.v(TAG, "Current Activity : " + mCurrentActivity.getClass().getName());
                    }
    });
    

    Regarding the class loader, if it consists of the main app classloader then you can retrieve it from LoadPackageParam passed to the handleLoadPackage method.

    If the app itself creates a new DexClassLoader then you can hook the DexClassLoader constructor to keep a reference to it. That way you have the actual ClassLoader that contains your class and method. No need to get any context.