在Activity的onCreate方法设置布局文件之前调用如下方法:
@SuppressLint("SoonBlockedPrivateApi")
public static void hookWebView() {
int sdkInt = Build.VERSION.SDK_INT;
try {
Class<?> factoryClass = Class.forName("android.webkit.WebViewFactory");
Field field = factoryClass.getDeclaredField("sProviderInstance");
field.setAccessible(true);
Object providerInstance = field.get(null);
if (providerInstance != null) {
LogUtils.info(TAG, "sProviderInstance isn't null");
return;
}
Method getProviderClassMethod;
if (sdkInt > MIN_SDK) {
getProviderClassMethod = factoryClass.getDeclaredMethod("getProviderClass");
} else if (sdkInt == MIN_SDK) {
getProviderClassMethod = factoryClass.getDeclaredMethod("getFactoryClass");
} else {
LogUtils.info(TAG, "Don't need to Hook WebView");
return;
}
getProviderClassMethod.setAccessible(true);
Class<?> factoryProviderClass = (Class<?>) getProviderClassMethod.invoke(factoryClass);
Class<?> delegateClass = Class.forName("android.webkit.WebViewDelegate");
Constructor<?> delegateConstructor = delegateClass.getDeclaredConstructor();
delegateConstructor.setAccessible(true);
if (sdkInt < ANDROID_0_SDK) {
Constructor<?> providerConstructor
= factoryProviderClass.getConstructor(delegateClass);
if (providerConstructor != null) {
providerConstructor.setAccessible(true);
providerInstance = providerConstructor
.newInstance(delegateConstructor.newInstance());
}
} else {
Field chromiumMethodName = factoryClass
.getDeclaredField("CHROMIUM_WEBVIEW_FACTORY_METHOD");
chromiumMethodName.setAccessible(true);
String chromiumMethodNameStr = (String) chromiumMethodName.get(null);
if (chromiumMethodNameStr == null) {
chromiumMethodNameStr = "create";
}
Method staticFactory = factoryProviderClass
.getMethod(chromiumMethodNameStr, delegateClass);
if (staticFactory != null) {
providerInstance = staticFactory.invoke(null,
delegateConstructor.newInstance());
}
}
if (providerInstance != null) {
field.set("sProviderInstance", providerInstance);
LogUtils.info(TAG, "Hook success!");
} else {
LogUtils.info(TAG, "Hook failed!");
}
} catch (Throwable ex) {
LogUtils.warn(TAG, String.valueOf(ex));
}
}