2015-04-23 78 views
8

我正在创建一个应用程序,它可以列出ListView中所有可用的无线网络。如果我在List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();之前缓存的列表中选择了一个wifi,那么它应该连接到它。如果WifiConfiguration列表不包含所选的wifi,则不会发生任何事情。我的问题是,有时我从列表中选择一个wifi(我知道它肯定在WifiConfiguration列表中),但它不连接到它。相反,它连接到以前连接的无线网络。经过一些尝试(一次又一次地选择相同的wifi),它最终连接到它。这不会总是发生,只是有时候。可能是什么问题?这里是我的代码片段:连接到特定的WiFi有时失败android

// Go through all the cached wifis and check if the selected GoPro was cached before 
for (WifiConfiguration config : configurations) { 
    // If it was cached connect to it and that's all 
    if (config.SSID != null && config.SSID.equals("\"" + mDrawerListView.getAdapter().getItem(position) + "\"")) { 
     // Log 
     Log.i("onReceive", "Connecting to: " + config.SSID); 
     mWifiManager.disconnect(); 
     mWifiManager.enableNetwork(config.networkId, true); 
     mWifiManager.reconnect(); 
     break; 
    } 
} 

回答

9

这就是发生了什么事。基本上,您可以告诉操作系统禁用网络,并且可以告诉操作系统启用网络,但无法告诉操作系统连接哪个网络。

如果设备上配置了两个范围内的多个WiFi接入点(且两者均处于enabled状态),则操作系统将决定要连接哪一个WiFi接入点。

强制操作系统连接到其中一个网络而不是另一个网络的唯一方法是在您不想连接的范围内的网络上拨打disableNetwork()

让我们通过代码逐行:

mWifiManager.disconnect(); 

线之上告诉操作系统从当前连接的WiFi接入点断开连接。

mWifiManager.enableNetwork(config.networkId, true); 

线之上告诉设备到网络设置为enabled状态,如果它在disabled状态以前。

mWifiManager.reconnect(); 

the documentation

重新连接到当前工作中的接入点,如果我们目前 断开。这可能会导致异步传递状态 更改事件。

所以,当你说而是它连接回到以前连接的WiFi。,它的工作与预期完全一致,因为操作系统重新连接到它认为的当前活动接入点

如果你真的要禁用其他网络,使操作系统将连接到您刚才点击的一个,你可以做这样的事情:

// Go through all the cached wifis and check if the selected GoPro was cached before 

WifiInfo info = mWifiManager.getConnectionInfo(); //get WifiInfo 
int id = info.getNetworkId(); //get id of currently connected network 

for (WifiConfiguration config : configurations) { 
    // If it was cached connect to it and that's all 
    if (config.SSID != null && config.SSID.equals("\"" + mDrawerListView.getAdapter().getItem(position) + "\"")) { 
     // Log 
     Log.i("onReceive", "Connecting to: " + config.SSID); 

     mWifiManager.disconnect(); 

     mWifiManager.disableNetwork(id); //disable current network 

     mWifiManager.enableNetwork(config.networkId, true); 
     mWifiManager.reconnect(); 
     break; 
    } 
} 
+0

感谢Daniel的简要解释!它是如何解释它真的很有意义!我远离了我正在开发的机器,但明天它将是第一个尝试它的机器! – Silex

+0

我刚刚测试出您的解决方案,并且完美地工作,谢谢! – Silex

+0

也许很重要的一点是,事情已经从Android 6开始改变了:https://developer.android.com/about/versions/marshmallow/android-6.0-changes.html#behavior-network据我所知,它将只能禁用网络,如果这个网络之前已被相同的应用程序所支持 – soey

0

嗨,而不是禁用以前的网络,你可以更改连接到的网络的优先级,而不是所有其他已配置的网络,然后再重新连接()。它将连接到范围内最高优先级的网络。

wificonfig.priority = 10000; 
wifiManager.updateNetwork(wificonfig); 
wifiManager.saveConfiguration(); 
wifiManager.disconnect(); 
wifiManager.enableNetwork(i.networkId, false); 
wifiManager.reconnect();