我创建了一个应用程序,用于从列表中连接到选定的Wifi。这在Android版本的4.1.2(网络ID = 10)中工作正常,但如果我尝试在版本4.4.2和4.4.4上运行相同的应用程序,它将网络ID值显示为-1。
我的代码是:
private void connectToWifi2() {
// TODO Auto-generated method stub
// Main method. Write code here.
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = String.format("\"%s\"", selWifi.SSID);
conf.preSharedKey = String.format("\"%s\"", pwd.getText().toString());
conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
conf.status = WifiConfiguration.Status.ENABLED;
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
conf.hiddenSSID = true;
// remember id
int netId = wifiManager.addNetwork(conf);
Log.d("RMGWiFiConfig", "netId returned" + netId);
if (netId >= 0) {
Log.i("RMGWiFiConfig", "Connecting with " + selWifi.SSID);
wifiManager.disconnect();
Boolean statusInBoolean = wifiManager.enableNetwork(netId, true);
Log.d("RMGWiFiConfig", "Enabled network returned "
+ statusInBoolean);
Log.d("RMGWiFiConfig", "Reassociate : " + wifiManager.reassociate());
Log.d("RMGWiFiConfig", "Reconnect " + wifiManager.reconnect());
} else {
Log.d("RMGWifiConfig", "Failed to add network configuration");
}
}
我尝试引用以下链接但无法解决问题。或者可能是我无法以下面链接中提供的正确方式适应解决方案。请让我知道我需要做的更改w.r.t我的代码。
Can not connect another android device with wifi with android lollipop
Android WifiConfiguration shows -1 for ID. How can I fix it for SSID to be recognized?
Android 6.0 Cannot add WifiConfiguration if there is already another WifiConfiguration for that SSID
android wifiManager.addNetwork returns -1
WifiConfiguration enable network in Lollipop
Android 5.0 Lollipop and 4.4 KitKat ignores my WiFi network, enableNetwork() is useless
请帮助!
由于 思鲁提
答案 0 :(得分:0)
我无法找到明显的关键原因,但我在Android 6.x上有类似的代码。我能找到的差异是:
wc.StatusField = WifiStatus.Disabled;
(enableNetwork()稍后会更新)wc.PreSharedKey = "\"" + pw + "\"";
wm.SaveConfiguration();
如果我不得不猜测,我会说这是导致失败的第一个。