强制WebView在特定网络上运行

win*_*rrr 4 networking android webview

是否可以WebView通过指定强制加载URL Network

我的设备有两个网络连接打开:wifi和移动数据.移动数据网络设置为传出连接的默认网络(因此连接管理器返回移动数据网络connectivityManager.getActiveNetwork()).

我正在尝试加载(来自http://10.0.0.1:80)的网页正在通过wifi连接的Web服务器上运行.因此,Web视图无法加载到页面,因为它无法通过移动数据加载.

win*_*rrr 6

所以我自己在这个主题中挖了一点,发现了一些有用的信息:

有了这些知识,我终于找到了一个有效的解决方案:

ConnectionFragment.java

public class ConnectionFragment extends Fragment {

    private static final String TAG = ConnectionFragment.class.getSimpleName();

    private final NetworkCallback networkCallback = new NetworkCallback();
    private ConnectivityManager connectivityManager;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        Log.v(TAG, "onCreate");
        super.onCreate(savedInstanceState);

        connectivityManager = (ConnectivityManager) getActivity().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    }

    @Override
    public void onStart() {
        Log.v(TAG, "onStart");
        super.onStart();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            registerNetworkCallback();
        }
    }

    @Override
    public void onStop() {
        Log.v(TAG, "onStop");
        super.onStop();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            unregisterNetworkCallback();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void registerNetworkCallback() {
        Log.v(TAG, "registerNetworkCallback");

        final NetworkRequest networkRequest = new NetworkRequest.Builder()
                .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                .build();

        connectivityManager.registerNetworkCallback(networkRequest, networkCallback);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void unregisterNetworkCallback() {
        Log.v(TAG, "unregisterNetworkCallback");
        connectivityManager.unregisterNetworkCallback(networkCallback);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private class NetworkCallback extends ConnectivityManager.NetworkCallback {

        @Override
        public void onAvailable(Network network) {
            Log.v(TAG, "onAvailable");
            bindProcessToNetwork(network);
        }

        @Override
        public void onLost(Network network) {
            Log.v(TAG, "onLost");
            bindProcessToNetwork(null);
        }

        private void bindProcessToNetwork(final Network network) {
            Log.v(TAG, "bindProcessToNetwork: " + network);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                connectivityManager.bindProcessToNetwork(network);
            } else {
                ConnectivityManager.setProcessDefaultNetwork(network);
            }
        }

    }

}
Run Code Online (Sandbox Code Playgroud)

我希望这会对某人有所帮助.

但请记住:对于依赖其他网络的所有其他连接,您需要手动配置套接字.

最好的问候,
winklerrr