0

我尝试获取可用网络列表,但当 WiFi 开启时,我只看到“WIFI”,尽管启用了 GSM/LTE。有没有获得可用网络列表的好方法?

我正在尝试这样做:

ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
String strNetworkName = "";
if(null != connManager) {
    Network networks[] = connManager.getAllNetworks();
    if(networks != null) {
         NetworkInfo nwInfo = null;
         for(Network nw: networks) {
             nwInfo = connManager.getNetworkInfo(nw);
             strNetworkName += nwInfo.getTypeName() + ", ";
        }
    }
}
Toast.makeText(getApplicationContext(), strNetworkName, Toast.LENGTH_SHORT).show();
4

1 回答 1

0

我开发了返回连接名称和网络映射的函数。我认为这可能很有趣。

Map<String,Network> getAvailableNetwoks(Context context) {
    ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    HashMap<String,Network> setNetworkName = new HashMap<String,Network>();
    if (null != connManager) {

        // Set MOBILE network for checking is it existing
        activateMobileNetwork(context, connManager);

        Network networks[] = connManager.getAllNetworks();
        if (networks != null) {
            NetworkInfo nwInfo;
            for (Network nw : networks) {
                nwInfo = connManager.getNetworkInfo(nw);
                setNetworkName.put(nwInfo.getTypeName(), nw);
            }
        }
    }

    return setNetworkName;
}

void activateMobileNetwork(Context context, ConnectivityManager connManager) {
    NetworkRequest.Builder builder = new NetworkRequest.Builder();
    builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
    builder.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);

    NetworkRequest networkRequest = builder.build();
    connManager.requestNetwork(networkRequest, new ConnectivityManager.NetworkCallback() {
        @Override
        public void onAvailable(Network network) {
            super.onAvailable(network);
            Toast.makeText(context, "MOBILE connect", Toast.LENGTH_SHORT).show();
        }
    });
}
于 2018-08-24T05:00:03.960 回答