Android WebView/APP全局设置代理(socks5)

72次阅读
没有评论

安卓10也同样适用

    public static boolean setProxy(WebView webview, String host, int port){
        Context appContext = webview.getContext().getApplicationContext();
        System.setProperty("socksProxyHost", host);
        System.setProperty("socksProxyPort", String.valueOf(port));
        try {
            Field loadedApkField = appContext.getClass().getField("mLoadedApk");
            loadedApkField.setAccessible(true);
            Object loadedApk = loadedApkField.get(appContext);
            @SuppressLint("PrivateApi") Class loadedApkCls = Class.forName("android.app.LoadedApk");
            Field receiversField = loadedApkCls.getDeclaredField("mReceivers");
            receiversField.setAccessible(true);
            ArrayMap receivers = (ArrayMap) receiversField.get(loadedApk);
            for (Object receiverMap : receivers.values()) {
                for (Object rec : ((ArrayMap) receiverMap).keySet()) {
                    Class clazz = rec.getClass();
                    if (clazz.getName().contains("ProxyChangeListener")) {
                        Method onReceiveMethod = clazz.getDeclaredMethod("onReceive", Context.class, Intent.class);
                        Intent intent = new Intent(android.net.Proxy.PROXY_CHANGE_ACTION);
                        onReceiveMethod.invoke(rec, appContext, intent);
                    }
                }
            }
            Log.d("====Debug", "Setting proxy successful!");
            return true;
        } catch (NoSuchMethodException | InvocationTargetException | NoSuchFieldException | IllegalAccessException | ClassNotFoundException e) {
            e.printStackTrace();
            return false;
        }
    }

不用的时候(webview加载完成后)

    public static boolean romeProxy(){
        try {
            System.setProperty("socksProxyHost", "");
            System.setProperty("socksProxyPort", "");
            return true;
        }catch (Exception e){
            return false;
        }
    }
迷鹿, lostfawn
版权声明:本站原创文章,由迷鹿, lostfawn2021-11-05发表,共计1384字。
转载提示:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
载入中...