[英]Connect to wifi network programmatically(first access ssid)?
I want to connect first time wifi network (one not saved before). 我想连接第一次wifi网络(之前没有保存过)。 If I connected to the wifi before, the code below runs well and I access wifi, but if I try first time to connect, nothing happens.
如果我之前连接到wifi,下面的代码运行良好,我访问wifi,但如果我第一次尝试连接,没有任何反应。 Why is this happening?
为什么会这样?
String networkSSID = "myssid";
String networkPass = "mypass";
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + networkSSID + "\"";
conf.preSharedKey = "\""+ networkPass +"\"";
WifiManager wifiManager = (WifiManager)MainActivity.this.getSystemService(Context.WIFI_SERVICE);
wifiManager.addNetwork(conf);
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;
}
}
A bit late, but it might help someone else. 有点晚了,但它可能会帮助别人。 You're, kind of, doing it wrong.
你是这样的,做错了。 You're adding a network (the one that hasn't been configured before) and then you try to connect to a configured network (a different one), both with the same SSID.
您正在添加一个网络(之前尚未配置的网络),然后您尝试连接到已配置的网络(另一个网络),两者都具有相同的SSID。 Instead, try this:
相反,试试这个:
netId = wifiManager.addNetwork(conf);
if (netId == -1) {
netId = //your procedure of getting the netId from wifiManager.getConfiguredNetworks()
}
wifiManager.enableNetwork(netId, true);
In Kotlin, it looks something like this: 在Kotlin中,它看起来像这样:
var netId = wifiManager.addNetwork(conf)
if (netId == -1) netId = getExistingNetworkId(ssid)
if (!wifiManager.enableNetwork(netId, true)) {
//Handle failure
}
...
private fun getExistingNetworkId(ssid: String): Int {
wifiManager.configuredNetworks?.let {
return it.firstOrNull { it.SSID.trim('"') == ssid.trim('"') }?.networkId ?: -1
}
//Unable to find proper NetworkId to connect to
return -1
}
This should suffice. 这应该足够了。 You don't need disconnect/reconnect part.
您不需要断开/重新连接部件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.