如果已连接到另一个WiFi,则连接到特定WiFi

时间:2017-12-01 12:12:42

标签: java android wifi

我已经两天像鱼一样战斗了,我找不到解决办法。我尝试了这段代码,但它在Android 5(Lollipop)上工作并且在7.1.1没有工作。(Nougat)我有另一个场景,手机失去连接,在此之后,它需要返回到旧的Wifi。

public void setWifiConnection1(View view){
  WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);


  WifiConfiguration wc = new WifiConfiguration();
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();

  wc.SSID = "\"NETWORK_NAME\"";
  wc.preSharedKey = "\"PASSWORD\"";
    wc.status = WifiConfiguration.Status.ENABLED;
    wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    wc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
    wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
    wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
    wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
    wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
    wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
    wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    wc.priority = 999999;
    wifiManager.setWifiEnabled(true);
    int netId = wifiManager.addNetwork(wc);
    if (netId == -1) {
        netId = getExistingNetworkId(wc.SSID);
    }
    wifiManager.disconnect();
    wifiManager.enableNetwork(netId, true);
    wifiManager.reconnect(); 
}

 private int getExistingNetworkId(String SSID) {

    WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

    List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks();
    if (configuredNetworks != null) {
        for (WifiConfiguration existingConfig : configuredNetworks) {
            if (existingConfig.SSID.equals(SSID)) {
                return existingConfig.networkId;
            }
        }
    }
    return -1;
}

1 个答案:

答案 0 :(得分:1)

  

wifiManager.setWifiEnabled(真);

您不能在此行之后立即执行代码。您应该执行 wifiManager.isWifiEnabled()检查并订阅广播(如果已禁用)。

下一步...

wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();

这部分很奇怪:为什么要断开连接?请注意,大多数WifiManager操作都是异步的,这就是为什么每次都会观察到不同的结果 - 在您尝试启用所需的网络后,可能会发生真正的“断开连接”。

您始终可以从系统API中获取灵感:https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r30/wifi/java/android/net/wifi/WifiManager.java#2773

正确的顺序是:

wifiManager.addNetwork(...);
wifiManager.enableNetwork(netId, true);
wifiManager.saveConfiguration();
wifiManager.reconnect();

但如果允许这样做,则直接使用系统API会更方便。