Trying to create a NFC tag app that stores Wifi credentials on a NFC tag then read it out. From there I take the string and use that to and put the credentials through wifimanager to connect to the wireless network. I'm pretty sure I have the code correct, but it's still not connecting. Am i missing something? The channel i'm trying to connect to is WPA2.
How i'm pulling the data for the function:
@Override
public void onClick(View v)
{
String payload = _textViewData.getText().toString();
String[] parts = payload.split("-");
String SSID = parts[0];
String Password = parts[1];
part1.setText(SSID);
part2.setText(Password);
connectToWifi(SSID, Password);
}
});
UPDATED: connect function
private void connectToWifi(final String networkSSID, final String networkPassword){
if (!wifiManager.isWifiEnabled()){
wifiManager.setWifiEnabled(true);
}
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = String.format("\"%s\"", networkSSID);
conf.preSharedKey = "\""+ networkPassword +"\"";
WifiManager wifiManager = (WifiManager)this.getSystemService(Context.WIFI_SERVICE);
wifiManager.addNetwork(conf);
List<WifiConfiguration> wifiList = wifiManager.getConfiguredNetworks();
for( WifiConfiguration i : wifiList ) {
if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.reconnect();
break;
}
}
}
UPDATE 2:
I switched my network to WPA and it worked, doesn't seem to work for WPA2, is that even possible?
For connecting WPA network you need to add passphrase like this:
conf.preSharedKey = "\""+ networkPass +"\"";
For Open network you need to do this:
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
Then, you need to add it to Android wifi manager settings:
WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
wifiManager.addNetwork(conf);
after that you have to enable it.
List<WifiConfiguration> wifiList = wifiManager.getConfiguredNetworks();
for( WifiConfiguration i : wifiList ) {
if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.status = WifiConfiguration.Status.ENABLED;
wifiManager.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wifiManager.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wifiManager.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wifiManager.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); wifiManager.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); wifiManager.allowedProtocols.set(WifiConfiguration.Protocol.RSN); wifiManager.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wifiManager.reconnect();
break;
}
}
Happy coding!!