我希望我的应用程序能够连接到Wi-Fi网络。
这个想法是要列出一组硬编码的网络,并且取决于我在哪里,该应用程序可以连接到另一个。
如果我处于网络范围内,当前我的应用可以连接到特定的Wi-Fi,并使用以下代码:
String ssid = "whateeverSSID";
String key = "passwordWIFI";
WifiConfiguration wfc = new WifiConfiguration();
WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(WIFI_SERVICE);
if (wifiManager.isWifiEnabled()) {
wfc.SSID = "\"".concat(ssid).concat("\"");
wfc.status = WifiConfiguration.Status.DISABLED;
wfc.priority = 40;
wfc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wfc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wfc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wfc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wfc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wfc.preSharedKey = "\"".concat(key).concat("\"");
netId = wifiManager.addNetwork(wfc);
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();
} else {
Toast.makeText(this, "Wifi Needs to be enabled for app to function.", Toast.LENGTH_LONG).show();
}
我尝试了一系列ssid wifi和循环,但没有用。
有什么主意我该如何连接到我所在范围内的Wi-Fi?