I have created an application to connect to selected Wifi from the list. This works fine in the android version of 4.1.2(network id = 10) but if I try to run the same application on version 4.4.2 and 4.4.4 it shows the network id value as -1.
My code to achieve this is :
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");
}
}
I tried to refer the below links but not able to resolve the problem. Or may be I am unable to fit in the solution in the right way provided in the below links.Please let me know the changes I need to do w.r.t my code.
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
Please Help!
Thanks
Shruti
I can't find an obvious critical reason, but I have similar code working on Android 6.x. The differences I can find are:
wc.StatusField = WifiStatus.Disabled; (enableNetwork() will update this later)
wc.PreSharedKey = "\"" + pw + "\"";
at the end: wm.SaveConfiguration();
If I had to guess, I'd say it was the first one that's causing the failure.
Related
I've been working on a react-native application recently, and I'd like to connect the devices to a wifi network through the app. I used the react-native-wifi npm lib to achieve this but it seems i have some problems connection with my android 9 phone. Although the lib is working with an other phone which is running android 7.1 (Nougat).
The ACCESS_FINE_LOCATION permission is granted in runtime by the user, also ACCESS_WIFI_STATE and CHANGE_WIFI_STATE are granted in the manifest.
So the native module that is used is:
public Boolean connectTo(ScanResult result, String password, String ssid, Promise promise) {
//Make new configuration
WifiConfiguration conf = new WifiConfiguration();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
conf.SSID = ssid;
} else {
conf.SSID = "\"" + ssid + "\"";
}
String capabilities = result.capabilities;
if (capabilities.contains("WPA") ||
capabilities.contains("WPA2") ||
capabilities.contains("WPA/WPA2 PSK")) {
// appropriate ciper is need to set according to security type used,
// ifcase of not added it will not be able to connect
conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
conf.status = WifiConfiguration.Status.ENABLED;
conf.preSharedKey = "\"" + password + "\"";
} else if (capabilities.contains("WEP")) {
conf.wepKeys[0] = "\"" + password + "\"";
conf.wepTxKeyIndex = 0;
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
} else {
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
}
//Remove the existing configuration for this netwrok
List<WifiConfiguration> mWifiConfigList = wifi.getConfiguredNetworks();
int updateNetwork = -1;
for (WifiConfiguration wifiConfig : mWifiConfigList) {
if (wifiConfig.SSID.equals(conf.SSID)) {
conf.networkId = wifiConfig.networkId;
updateNetwork = wifi.updateNetwork(conf);
}
}
// If network not already in configured networks add new network
if (updateNetwork == -1) {
updateNetwork = wifi.addNetwork(conf);
wifi.saveConfiguration();
}
if (updateNetwork == -1) {
return false;
}
boolean disconnect = wifi.disconnect();
if (!disconnect) {
return false;
}
boolean enableNetwork = wifi.enableNetwork(updateNetwork, true);
if (!enableNetwork) {
return false;
}
return true;
}
(returning false means the connection didnt succeed)
I was debugging it and it seems that wifi.updateNetwork(conf) and wifi.addNetwork(conf) always return -1 no matter what (so far). By the android docs these methods should still work with the API level 28.
I'm trying to connect to a WPA2 network. Also i tried to remove the network from the wifi.getConfiguredNetworks() list but didn't change anything.
I don't know what i'm missing, but i'd be really happy if somebody could help me out with this one.
Thanks!
After all i managed to find the solution which is really simple, just had to quote the ssid and it works. Tested on API level 27 and 28.
Premise:
I'm currently work on an Android App (API level 23, Android 6.0) that connect with a device via Wi-Fi and uses UDP packets to communicate. I'm able to change the device Wi-Fi password using a particular command. This works fine.
Target:
What I'm tring to programmatically do is:
search Wi-Fi generated from the device
connect to the device
send the command to change the password
reconnect to the device using the new password
I'm able to connect the first time (steps 1,2,3) using code like this:
private void connect(String ssid, String password) {
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = String.format("\"%s\"", ssid);
conf.preSharedKey = String.format("\"%s\"", password);
netId = mWifiManager.addNetwork(conf);
mWifiManager.saveConfiguration();
mWifiManager.disconnect();
mWifiManager.enableNetwork(netId, true);
mWifiManager.reconnect();
}
Additional info:
In the Manifest file I declared these permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
The problem:
If I try to use the same method to connect after the change of the password, I'm not able to achive the connection because (I think) Android remembers the previous password.
If I try to use updateNetwork(conf) instead of addNetwork(conf), I don't notice any difference.
I've tried to remove or disable in some ways the saved network before try to connect again, but unsaccesfully.
mWifiManager.removeNetwork(netId)
returns false (I have no idea why it fails)
mWifiManager.disableNetwork(netId);
returns true but it appears to have no effects
If I use the Android settings to change password, all works fine... but I want to change the saved password programmatically.
Any help is very appreciated
After several attempts, I currently have no problems following the instructions I report below.
Before connecting to a Wi-Fi network it is important to check the list of previously saved networks. If there is no network with the same SSID it is possible to create a new configuration, otherwise it is necessary to modify the existing one.
public void connect(String ssid, String password) {
WifiConfiguration wifiConf = null;
WifiConfiguration savedConf = null;
//existing configured networks
List<WifiConfiguration> list = mWifiManager.getConfiguredNetworks();
if(list!=null) {
for( WifiConfiguration i : list ) {
if (i.SSID != null && i.SSID.equals("\"" + ssid + "\"")) {
Log.d(TAG, "existing network found: " + i.networkId + " " + i.SSID);
savedConf = i;
break;
}
}
}
if(savedConf!=null) {
Log.d(TAG, "coping existing configuration");
wifiConf = savedConf;
} else {
Log.d(TAG, "creating new configuration");
wifiConf = new WifiConfiguration();
}
wifiConf.SSID = String.format("\"%s\"", ssid);
wifiConf.preSharedKey = String.format("\"%s\"", password);
int netId;
if(savedConf!=null) {
netId = mWifiManager.updateNetwork(wifiConf);
Log.d(TAG, "configuration updated " + netId);
} else {
netId = mWifiManager.addNetwork(wifiConf);
Log.d(TAG, "configuration created " + netId);
}
mWifiManager.saveConfiguration();
mWifiManager.disconnect();
mWifiManager.enableNetwork(netId, true);
mWifiManager.reconnect();
}
Android after version 6 does not allow any application to modify Wi-Fi networks unless it has been created by the application itself. In addition, it does not allow adding Wi-Fi networks with the same name as others already configured previously. This is very curious because when you configure Wi-Fi networks manually from the settings, it does allow it.
After thinking for a long time about a possible solution it occurred to me that perhaps the Wifi network could be added with another name and once added, change it to the desired name. I have tried it and it works. It would be something like the following:
int networkId = -1;
// Find my Wifi
List<WifiConfiguration> configuredWifis = wifiManager.getConfiguredNetworks();
for(WifiConfiguration wifi : configuredWifis)
{
if(wifi.SSID != null && wifi.SSID.equals("\"" + WIFI_SSID + "\"") && wifi.priority == WIFI_PRIORITY)
{
networkId = wifi.networkId;
}
else
{
wifiManager.disableNetwork(wifi.networkId);
wifiManager.removeNetwork(wifi.networkId); // After android 6 it really does not remove the Wifi network
wifiManager.saveConfiguration();
}
}
if(networkId == -1)
{
// If my Wifi is not yet configured then add it
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + WIFI_SSID + "\"";
conf.preSharedKey = "\""+ WIFI_PASSW +"\"";
conf.priority = WIFI_PRIORITY;
networkId = wifiManager.addNetwork(conf);
if(networkId == -1) // This ocurs when a wifi with the same name is yet configured. After Android 6 is not possible modify it.
{
Random random = new Random(System.currentTimeMillis());
int randomInteger = random.nextInt(10000);
conf.SSID = "\"" + WIFI_SSID + randomInteger + "\"";
networkId = wifiManager.addNetwork(conf); // Add my wifi with another name
conf.SSID = "\"" + WIFI_SSID + "\"";
conf.networkId = networkId;
networkId = wifiManager.updateNetwork(conf); // After my wifi is added with another name, I change it to the desired name
}
}
// Connect to my wifi
if(wifiManager.getConnectionInfo().getNetworkId() != networkId)
{
wifiManager.disconnect();
wifiManager.enableNetwork(networkId, true);
wifiManager.reconnect();
}
I just tried few codes for wpa2 enterprise connection in android but nothing is connecting i want a right code to connect the right network. right now i have used this answer but i need few clarification because this answer is very old one. here i am attaching some screenshot about connection clarification.
In this you can see identity and password
WifiConfiguration wifiConfiguration = new WifiConfiguration();
wifiConfiguration.SSID = "\"" + networkSSID + "\"";
wifiConfiguration.BSSID = Bssid;
wifiConfiguration.hiddenSSID = true;
wifiConfiguration.status = WifiConfiguration.Status.DISABLED;
wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wifiConfiguration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wifiConfiguration.enterpriseConfig.setIdentity(identity);
wifiConfiguration.enterpriseConfig.setPassword(password);
wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
if (networkPasskey.matches("^[0-9a-fA-F]+$")) {
wifiConfiguration.wepKeys[0] = networkPasskey;
} else {
wifiConfiguration.wepKeys[0] = "\"".concat(networkPasskey).concat("\"");
}
wifiConfiguration.wepTxKeyIndex = 0;
i have found enterprice function in wificonfiguration to set identity and password.
wifiConfiguration.enterpriseConfig.setIdentity(identity);
wifiConfiguration.enterpriseConfig.setPassword(password);
but what is the use of this one. when we have identity and password.
if (networkPasskey.matches("^[0-9a-fA-F]+$")) {
wifiConfiguration.wepKeys[0] = networkPasskey;
} else {
wifiConfiguration.wepKeys[0] = "\"".concat(networkPasskey).concat("\"");
}
wifiConfiguration.wepTxKeyIndex = 0;
i am using BSSID because my AP have same ssid so i want to connect the right network by using BSSID
I have solved it by the help of this link
WifiConfiguration config = new WifiConfiguration();
config.SSID = "\"" + networkSSID + "\"";
config.BSSID = Bssid;
config.priority = 1;
String networkIdentity = "";
networkPasskey = "";
config.status = WifiConfiguration.Status.ENABLED;
WifiEnterpriseConfig enterpriseConfig = new WifiEnterpriseConfig();
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
enterpriseConfig.setIdentity(networkIdentity);
enterpriseConfig.setPassword(networkPasskey);
enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.PEAP);
enterpriseConfig.setPhase2Method(WifiEnterpriseConfig.Phase2.MSCHAPV2);
config.enterpriseConfig = enterpriseConfig;
WifiManager myWifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
int id = myWifiManager.addNetwork(config);
Log.d("addNetwork", "# addNetwork returned " + id);
myWifiManager.enableNetwork(id, true);
but this method will work till android 7.0 in android 8.0 they have restricted many function we can not add wifi configuration manually.
three things we must know when you are trying to configure with wpa2 enterprise
you must know the EAP method it can be anything but mostly they will use PEAP
2.you must know about the Phase2 method, mostly they will use MSCHAPV2
Certificate this one maximum Do Not validate.
While using this to connect to an open WiFi network (that is not configured yet on the device):
public static void connectToWifiNetwork(Context context, final String ssid, String password) {
final WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.disconnect();
// Delete already available network
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for (WifiConfiguration i : list) {
if(i.SSID != null && i.SSID.equals("\"" + ssid + "\"")) {
Log.i(TAG, "Deleting configuration for " + ssid);
wifiManager.removeNetwork(i.networkId);
break;
}
}
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + ssid + "\"";
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
Log.d(TAG, "Added network " + ssid + " " + password);
final int addNetworkResult = wifiManager.addNetwork(conf);
new Thread(new Runnable() {
#Override
public void run() {
Log.d(TAG, "Attempting to connect to " + ssid + " with id " + addNetworkResult);
wifiManager.enableNetwork(addNetworkResult, true);
}
}).start();
}
On Nexus 5 with API 23 (6.0.1), the added network has result -1, does not connect.
On Nexus 5X with API 26 (8.0.0), the added network has result 2, connects fine.
I am building for target API 25.
I am not sure if it is about the API level or the device, but I'd like to have a solution to rule them all.
Any ideas?
Edit:
Also tried with ALL the configurations as in this SO question:
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
conf.allowedAuthAlgorithms.clear();
conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
Didn't work on Nexus 5 as well.
Note: I can connect to WEP/WPA/WPA2 programmatically using both devices by using this implementation.
For some reason, I had to manually delete the open network from Android's WiFi settings (even though connecting through it works fine). It now connects, but not every time.
It disconnects from current network, tries to connect to the open network, then connects to the previous network again.
I am trying to connect to a specific wifi network, as described here. However, while sometimes it works, most of the times it doesn't. I do not really understand why if I run the app, let's say 10 times, the device connects to my network 2 times, and the other 8 it doesn't.
In the following is the code I use in a Fragment.
WifiConfiguration wificonfiguration = new WifiConfiguration();
wificonfiguration.SSID = "\"" + networkSSID + "\"";
wificonfiguration.priority = 40;
wificonfiguration.status = WifiConfiguration.Status.ENABLED;
// WPA management
wificonfiguration.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
wificonfiguration.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wificonfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wificonfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wificonfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wificonfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
wificonfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
wificonfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wificonfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wificonfiguration.preSharedKey = "\"" + networkPass + "\"";
WifiManager wifiManager = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
int networkId = wifiManager.addNetwork(wificonfiguration);
if (networkId > -1) {
boolean status = wifiManager.enableNetwork(networkId, true);
}
The network configuration is actually added to the manager and status value is true. I have run it on several devices running Lollipop. Also, the network I want to connect to does not provide internet access, so I also thought that may be a problem for what stated in the note here. Can anybody tell me if the code is ok?
Solved
The problem was solved by adding wifiManager.disconnect(); before adding the new network configuration.
You could disable all the network via below described method before adding the network. This would disable all the configured networks to auto-connect.
for (WifiConfiguration wifiConfiguration_ : wifiManager.getConfiguredNetworks()) {
wifiConfiguration_.status = WifiConfiguration.Status.DISABLED;
int returnNetworkId_ = wifiManager.updateNetwork(wifiConfiguration_);
}