I am trying to connect with specific wifi but it is not working. Whenever i call a below code, already connected wifi stop and phone showing a wifi in scanning mode. Can someone tell me why this is happening. Here is my code:
String result = "";
try {
WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = String.format("\"%s\"", ssid);
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
int netId = wifiManager.addNetwork(wifiConfig);
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();
int state = wifiManager.getWifiState();
Log.i(TAG, "state: " + state);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String newSSID = wifiInfo.getSSID();
result = "Connected";
} catch (Exception e) {
result = "Failed";
Log.e(TAG, "unable to set wifi " + ssid, e);
}
I think you should not add SSID again. This code wifiManager.addNetwork(wifiConfig)
is adding another wifi profile to your device.
You just need below code to reconnect
private boolean connectToWifi(String ssid) {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
List<WifiConfiguration> wifiList = wifiManager.getConfiguredNetworks();
for( WifiConfiguration config : wifiList ) {
if(config.SSID != null && config.SSID.equals("\"" + ssid + "\"")) {
wifiManager.disconnect();
wifiManager.enableNetwork(config.networkId, true);
wifiManager.reconnect();
return true;
}
}
return false;
}