编程连接特定Wi-Fi网络:为何需先调用disconnect()?
disconnect() before enabling a specific WiFi SSID? Great question! Let’s break down why that disconnect() call is such a common (and often necessary) step in Android WiFi connection code. First, let’s recap your working code for context:
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks(); for( WifiConfiguration i : list ) { if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) { wifiManager.disconnect(); wifiManager.enableNetwork(i.networkId, true); wifiManager.reconnect(); break; } }
Here are the key reasons for including disconnect():
Clear stale connection state: Android’s
WifiManagercan sometimes hold onto an active or pending connection session. If you skipdisconnect()and callenableNetwork()directly, the system might ignore or delay your request because it’s still trying to maintain the existing connection.disconnect()forces a clean slate, ensuring the manager processes your new network enable request properly.Break priority-based connection locks: If your device is already connected to another WiFi network with higher priority (or the system defaults to keeping the current connection alive),
enableNetwork()alone might not trigger a switch.disconnect()cuts the existing link, removing that priority barrier so the system can prioritize your target SSID.Ensure
reconnect()targets the right network: On some devices,reconnect()will only attempt to rejoin the currently active network—even if you just enabled a different one. By disconnecting first, you ensure that the subsequentreconnect()initiates a full connection handshake with your desired SSID, not the previous one.
It’s worth noting that in rare cases (like if the device is already disconnected), this call might seem redundant. But given the variability in Android ROMs across manufacturers and versions, including disconnect() makes your code far more reliable and compatible across different devices.
内容的提问来源于stack exchange,提问作者Pritam

