android.uid.system和webview冲突解决方案

在做一款系统应用的时候用到WebView这个控件.但是在编译的时候直接就出错了.抛出For security reasons, WebView is not allowed in privileged processes

原因是因为Android在5.1版本以后不允许系统应用使用WebView导致的问题.

可以人为的更改那个变量来进行使用

PS:要在使用WebView前使用

// 如果是非系统进程则按正常程序走
if (Process.myUid() != Process.SYSTEM_UID) {
    return;
}
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) {
        LG.e("sProviderInstance isn't null");
        return;
    }

    Method getProviderClassMethod;
    if (sdkInt > 22) {
        getProviderClassMethod = factoryClass.getDeclaredMethod("getProviderClass");
    } else if (sdkInt == 22) {
        getProviderClassMethod = factoryClass.getDeclaredMethod("getFactoryClass");
    } else {
        LG.e("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 < 26) {//低于Android O版本
        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);
        LG.e("lmy","Hook success!");
    } else {
        LG.e("lmy","Hook failed!");
    }
} catch (Exception e) {
    LG.e("lmy", "hookWebView error",e);
}

你可能感兴趣的:(Android,View)