I am trying to save a Wi-Fi Enterprise Network in android. This code is working until Android 9 or lower but not above.
public static boolean connectToEnterprise(Context context, String ssid, String identity, String password) {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = "\"" + ssid + "\"";
wifiConfig.preSharedKey = "\"" + password + "\"";
// Set the EAP parameters
wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
wifiConfig.enterpriseConfig = new WifiEnterpriseConfig();
wifiConfig.enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.PEAP);
wifiConfig.enterpriseConfig.setPhase2Method(WifiEnterpriseConfig.Phase2.MSCHAPV2);
wifiConfig.enterpriseConfig.setIdentity(identity);
wifiConfig.enterpriseConfig.setPassword(password);
int netId = wifiManager.addNetwork(wifiConfig);
if (netId != -1) {
// Save the configuration and enable it.
wifiManager.saveConfiguration();
wifiManager.disableNetwork(netId);
wifiManager.disconnect();
turnOffAndOnWifi(wifiManager);
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();
return true;
} else {
// Failed to add the network configuration.
return false;
}
}
I tried addNetworkSuggestions method told in in [android docs]
(https://developer.android.com/reference/android/net/wifi/WifiManager#addNetwork(android.net.wifi.WifiConfiguration)
but it connects only when network is in range and also does not save that network in the device.
When it works
addNetwork method works when I set android app targetSdk=28. Then it also works on all devices. But then I can't upload app to playstore because to upload playstore targetSdk should be 31 for now.
I want it to save the Wi-Fi network in the device.