同时连接到局域网和互联网?

时间:2015-07-30 01:24:15

标签: android android-wifi android-networking

简单地说,我想使用我的Android设备连接到局域网但不会失去我的互联网功能。

我已经通过Google的网络连接指南进行了挖掘,但我找到的唯一可行解决方案是Wi-Fi Direct。不幸的是,我不认为这是可能的,因为局域网不支持Wi-Fi Direct协议。

有没有办法连接到没有互联网的Wi-Fi接入点并且仍然连接到具有互联网的蜂窝或以前的Wi-Fi接入点?

重新配置局域网是我能做的,如果有帮助的话

编辑:我看过this question,但看起来没有答案,而且3年前被问过

1 个答案:

答案 0 :(得分:1)

您需要构建一个知道只使用WiFi的HttpClient。

Android将检查互联网连接是否可以与他们一起上网,如果不能,则忽略它们。即使对于本地IP地址,也可能是一种痛苦。

这是我写的用于创建正确配置的OkHttp客户端的Dagger模块的一部分。

/**
 * Find the WiFi Network object. If the WiFi is off this will return null. You might want to listen to the broadcasts from the WiFi system to retry when the WiFi is turned on.
 */
@Provides
public Network provideNetwork(ConnectivityManager connectivityManager) {
    for (final Network network : connectivityManager.getAllNetworks()) {
        final NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
        final int networkType = networkInfo.getType();

        if (networkType == ConnectivityManager.TYPE_WIFI) {
            return network;
        }
    }

    return null;
}


/**
 * Create a HttpClient that will only use the network supplied. Changing this for the built in Apache HttpClient should be easy enough. 
 */
@Provides
public OkHttpClient provideOkHttpClient(final Network network) {
    if (network != null) {
        final OkHttpClient httpClient = new OkHttpClient();
        httpClient.setSocketFactory(network.getSocketFactory());

        Internal.instance.setNetwork(httpClient, new com.squareup.okhttp.internal.Network() {
            @Override
            public InetAddress[] resolveInetAddresses(String host) throws UnknownHostException {
                return network.getAllByName(host);
            }
        });

        return httpClient;
    }

    return null;
}
相关问题