Xposed技术问题:如何在应用启动时获取所有应用的Context
I get it—you're trying to hook every app to grab their Context, but your current code only works for some apps. Let's break down why that's happening and fix it with a more robust approach.
First, let's look at the limitations of your original code
Your current implementation hooks ContextWrapper.getApplicationContext() and stores the first applicationContext it gets. This has two big issues:
- You're overwriting (or ignoring) subsequent Context instances from other apps since you're using a single global variable.
- Not all apps or components will call
getApplicationContext()early enough (or at all) during their startup, so you'll miss some contexts entirely.
Here's a better approach to capture Context for every app
We need to hook key lifecycle methods that every app must go through, and handle each app's Context individually instead of using a global variable.
Step 1: Hook Application.onCreate() for each app
Every Android app creates an Application instance on startup, and its onCreate() method is guaranteed to run. This is the most reliable place to get the app's Context.
Step 2: Add a fallback hook for ContextWrapper.attachBaseContext()
Some apps or components might initialize their Context before Application.onCreate(), so hooking this method covers those edge cases.
Optimized Code Example
@Override public void handleLoadPackage(XC_LoadPackage.LoadPackageParam lpparam) throws Throwable { // Skip system framework if you don't need it (optional) if (lpparam.packageName.equals("android")) { return; } // Hook Application.onCreate() to get the app's core Context try { Class<?> applicationClass = XposedHelpers.findClass("android.app.Application", lpparam.classLoader); XposedHelpers.findAndHookMethod(applicationClass, "onCreate", new XC_MethodHook() { @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { super.afterHookedMethod(param); // 'thisObject' is the Application instance, which is a Context Context appContext = (Context) param.thisObject; String packageName = appContext.getPackageName(); // Do your initialization for this specific app here initForApp(appContext, packageName); XposedBridge.log("Successfully retrieved Context for: " + packageName); } }); } catch (Throwable t) { XposedBridge.log("Failed to hook Application.onCreate() for " + lpparam.packageName + ": " + t.getMessage()); } // Fallback hook: ContextWrapper.attachBaseContext() try { Class<?> contextWrapperClass = XposedHelpers.findClass("android.content.ContextWrapper", lpparam.classLoader); XposedHelpers.findAndHookMethod( contextWrapperClass, "attachBaseContext", Context.class, new XC_MethodHook() { @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { super.afterHookedMethod(param); Context baseContext = (Context) param.args[0]; String packageName = baseContext.getPackageName(); // Optional: Check if you already processed this app to avoid duplicates if (!hasProcessedApp(packageName)) { initForApp(baseContext, packageName); XposedBridge.log("Retrieved base Context for: " + packageName); } } } ); } catch (Throwable t) { XposedBridge.log("Failed to hook ContextWrapper.attachBaseContext() for " + lpparam.packageName + ": " + t.getMessage()); } } // Example helper methods private Map<String, Context> appContexts = new HashMap<>(); private void initForApp(Context context, String packageName) { appContexts.put(packageName, context); // Your initialization logic here (e.g., set up hooks for this app) } private boolean hasProcessedApp(String packageName) { return appContexts.containsKey(packageName); }
Key Improvements Explained
- Per-app handling: We hook methods within each app's
handleLoadPackage()call, using the app's ownClassLoader—no cross-app conflicts. - Reliable Context source:
Application.onCreate()gives us the app's root Context, which is valid for the entire lifecycle of the app. - Avoid duplicates: Using a
Mapto track processed apps ensures we don't run initialization logic multiple times for the same app. - Edge case coverage: The
attachBaseContext()hook catches Context instances that might be created before the Application'sonCreate().
Additional Notes
- Custom Application classes: Even if an app uses a custom subclass of
Application, our hook will still work because we're targeting the parentandroid.app.Applicationclass. - System apps: Some system apps might restrict Xposed hooks. Make sure your module is enabled for these apps in the Xposed Installer settings.
- Performance: Avoid heavy operations in the hook methods—offload any slow work to an asynchronous thread to prevent delaying app startup.
内容的提问来源于stack exchange,提问作者Leon

