问题
so I have trawled true all threads in here and any where else where google would take me. But still I am having problems connecting to WPA PSK networks. Here is my code, I have 2 edittext fields from which I read SSID and PSK and then one checkbox to select if SSID is hidden or not.
EditText mSSID = (EditText) findViewById(R.id.wifiTVssidcurrent);
String networkSSID = mSSID.getText().toString();
EditText mWPA = (EditText) findViewById(R.id.wifiTVwpacurrent);
String networkWPA = mWPA.getText().toString();
// Update text to show that connection is pending
TextView wifiStatus = (TextView) findViewById(R.id.wifiTVconnectionstatus);
wifiStatus.setText("Connecting to " + networkSSID);
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiConfiguration wc = new WifiConfiguration();
wc.SSID = "\"".concat(networkSSID).concat("\"");
wc.preSharedKey = "\"".concat(networkWPA).concat("\"");
CheckBox mSSIDHidden = (CheckBox) findViewById(R.id.wifiCBhiddenssid);
wc.hiddenSSID = false;
if (mSSIDHidden.isChecked()) {
wc.hiddenSSID = true;
}
wc.status = WifiConfiguration.Status.ENABLED;
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
int res = wifi.addNetwork(wc);
Log.d("WifiPreference", "add Network returned " + res );
boolean b = wifi.enableNetwork(res, true);
Log.d("WifiPreference", "enableNetwork returned " + b );
boolean c = wifi.reconnect();
Log.d("WifiPreference", "reconnect returned " + c );
What I see in the phone after running this is that an AP is created in settings, but it is not connecting. And if I try to use the created AP manually from settings afterwards I am not able to connect either. But if I create the AP from within settings I get connection as I should.
As for putting SSID and WPA PSK in I have tried both "\"".concat(networkSSID).concat("\""); and "\""+ networkSSID +"\""; with same result.
Any tips will be very welcome. Best regards Lasse
回答1:
Again big thanks to Ryan for proposing how to read the settings created by the OS.
So I thought I had tried everything suggested here on stack overflow. But this thread actually helped me in the end Setup wifi programatically using WPA Security in android tablet So big thanks to RYAN for providing the tips on reading one AP and then mimmick it. In my case it turned out that I needed to add Even though I am setting up for WPA I still needed to add allowedGroupCiphers WEP40 and WEP104 And I only had
`wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN); //So I also added
wc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);`
来源:https://stackoverflow.com/questions/9725830/android-using-wifimanager-to-connect-to-wpa-psk-secured-network