In my application i want to connect to specific wifi connection. My application is working fine till version 19. when install application android 6.0 , addNetwork always return "-1".
Below is the code i am using.
private int configureNetworkAndReturnId() {
WifiConfiguration config = new WifiConfiguration();
config.BSSID = "xx:xx:xx:xx:xx:xx";
config.SSID = "\"" + "Name" + "\"";
config.priority = 1;
config.status = WifiConfiguration.Status.ENABLED;
// Set connection configuration to require encryption
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
config.preSharedKey = "xxxx";
final int newId = wifiManager.addNetwork(config);
Log.d(TAG, "Created new network configuration, ID: " + newId + ", Config: " + config);
return newId;
}
Since above method is returning -1, when i call boolean isEnabled = wifiManager.enableNetwork(id, true); application is struck .
Anyone faced same issue?
If network id is -1, then read the network id from the existed configured network. If it is available in network list it return the id.
int newId = wifiManager.addNetwork(config);
if (newId == -1) {
// Get existed network id if it is already added to WiFi network
newId = getExistingNetworkId(SSID);
Log.d(TAG, "getExistingNetworkId: " + newId);
}
private int getExistingNetworkId(String SSID) {
List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks();
if (configuredNetworks != null) {
for (WifiConfiguration existingConfig : configuredNetworks) {
if (SSID.equalsIgnoreCase(existingConfig.SSID)) {
return existingConfig.networkId;
}
}
}
return -1;
}
Was the Wifi network you are attempting to connect configured by some other App? You can try forgetting the Wifi network from Settings and then try.
See the Marshmallow release notes. There is a change here that if Wifi was not configured by your App, then it cannot be modified.
Related
"Addnetwork" is used below Android 9.0. This method returns correctly, but it fails when Android 10.0 is used. It always returns - 1. What is the reason?
This is my core code:
public WifiConfiguration createWifiInfo(String SSID, String Password,
int Type) {
WifiConfiguration config = new WifiConfiguration();
config.allowedAuthAlgorithms.clear();
config.allowedGroupCiphers.clear();
config.allowedKeyManagement.clear();
config.allowedPairwiseCiphers.clear();
config.allowedProtocols.clear();
config.SSID = "\"" + SSID + "\"";
WifiConfiguration tempConfig = this.isExsits(SSID);
if (tempConfig != null) {
mWifiManager.removeNetwork(tempConfig.networkId);
}
if (Type == 1) // WIFICIPHER_NOPASS
{
config.wepKeys[0] = "";
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
}
return config;
}
Partial code:
WifiConfiguration wifiInfo = createWifiInfo("", "", 1);
networkId = mWifiManager.addNetwork(wifiInfo);//result: networkId:-1
WifiManager.addNetwork(WifiConfiguration config) has been deprecated in API level 29.
Instead, developers are expected to use the WifiNetworkSpecifier or "Wi-Fi suggestion API" as stated in the link above. Both APIs show a different system dialog which asks the user to connect to a specified network.
You can find an example for the WifiSuggestions API in this StackOverflow thread: Creating a custom wifi setup
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 am creating an Android app which allows to connect you to a WiFi with a specific BSSID. I have implemented the part which scan all the wifis and make the WiFi configuration in function of WiFi network security type. I have also implemented the connection to WiFi network with a specific BSSID.
But I have a problem: the connection to a specific BSSID works well for secure networks but doesn't work really for open network and I don't know why. Indeed this connection to an open network with a specific BSSID works on Samsung Galaxy S4 or more recent but doesn't work on Galaxy S2 and S3 ... It's really weird. On S2 and S3 the BSSID isn't take into account during connection.
This is the sample code that I use to create the configuration for a open network and try to connect on it with the specific BSSIDs:
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + wifiItem.getSSID() + "\"";
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
WifiManager wifiManager = (WifiManager) parentActivity.getSystemService(Context.WIFI_SERVICE);
wifiManager.addNetwork(conf);
conf.BSSID = wifiItem.getBSSID();
wifiManager.updateNetwork(conf);
wifiManager.saveConfiguration();
for (WifiConfiguration wifiConfiguration : wifiManager.getConfiguredNetworks()) {
if (wifiConfiguration.SSID.equals("\"" + wifiItem.getSSID() + "\"")) {
wifiManager.disconnect();
wifiConfiguration.BSSID = wifiItem.getBSSID();
wifiManager.updateNetwork(wifiConfiguration);
wifiManager.enableNetwork(wifiConfiguration.networkId, true);
wifiManager.reconnect();
}
If someone could help me it would be so cool. I spent a lot of time on it and really don't understand this problem.
You can try looking this code over, this is what we use to connect to networks:
private void connectToNetwork(String password, ScanResult result, String capabilities) {
WifiConfiguration wc = new WifiConfiguration();
wc.SSID = "\"" + result.SSID + "\"";
wc.hiddenSSID = true;
wc.status = WifiConfiguration.Status.ENABLED;
if (capabilities.contains("WPA2")) {
wc.preSharedKey = "\"" + password + "\"";
wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
}
if (capabilities.contains("WPA")) {
wc.preSharedKey = "\"" + password + "\"";
wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
}
if (capabilities.contains("WEP")) {
wc.wepKeys[0] = password;
wc.wepTxKeyIndex = 0;
wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
}
if (capabilities.contains("TKIP")) {
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
}
if (capabilities.contains("CCMP")) {
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wc.allowedKeyManagement.set(WifiConfiguration.PairwiseCipher.CCMP);
}
if (!hasWifiSecurity(capabilities)) {
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.NONE);
wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
}
// wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
// // wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
// wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
int res = wifi.addNetwork(wc);
Log.d("WifiPreference", "add Network returned " + res);
boolean b = wifi.enableNetwork(res, true);
Log.d("WifiPreference", "enableNetwork returned " + b);
Log.d("", "Reassociate: " + wifi.reassociate());
Log.d("", "ReConnect: " + wifi.reconnect());
wifi.saveConfiguration();
WifiInfo connection = wifi.getConnectionInfo();
if (connection != null) {
if (connection.getSupplicantState().equals(SupplicantState.INACTIVE)) {
wifi.removeNetwork(res);
wifi.saveConfiguration();
scanForWiFiNetworks();
wifi.enableNetwork(wifi.getConnectionInfo().getNetworkId(), true);
}
}
// scanForWiFiNetworks();
// if (password.equalsIgnoreCase("")) {
// setScanningEnabled(true);
// }
// Toast.makeText(con, "Connecting to network: " + connectionInfo, Toast.LENGTH_SHORT).show(getMessageComments(dialog.getTextID()));
}
We need to connect to a 5G network with the same SSID as the 2.4G network, so the only way is to set the BSSID. i've just successfully connected to the several specified BSSID networks with the code below, have a try:
WifiConfiguration config = new WifiConfiguration();
config.allowedAuthAlgorithms.clear();
config.allowedGroupCiphers.clear();
config.allowedKeyManagement.clear();
config.allowedPairwiseCiphers.clear();
config.allowedProtocols.clear();
config.SSID = "\"" + SSID + "\"";
config.BSSID = BSSID; // <--BSSID should be set without ->"<- (-__-)b...
// remove this network from the configed(saved) network list
List<WifiConfiguration> existingConfigs = mWifiManager.getConfiguredNetworks();
for (WifiConfiguration existingConfig : existingConfigs)
{
if (null != existingConfig && existingConfig.SSID.toString().equals("\"" + SSID + "\""))
{
mWifiManager.removeNetwork(existingConfig.networkId);
}
}
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
//...
//...
// get the networkid
int wcgID = mWifiManager.addNetwork(config);
// enabled this network
boolean b = mWifiManager.enableNetwork(wcgID, true);
I am trying setup WiFi programatically on an Android tablet. If there is no WiFi connection then add the network with SSID and passkey read from a text file. Adding this network to network list and saving the passkey. It's adding the network and saving the passkey also but when I try to connect, it's not connecting. let me know...
public static void setupWifi(Context _context)
{
if(deviceConfig.wireless_ssid.length()==0) return;
WifiManager wifi = (WifiManager)_context.getSystemService(_context.WIFI_SERVICE);
WifiConfiguration wc = new WifiConfiguration();
wc.SSID = "\"" + deviceConfig.wireless_ssid + "\""; //IMP! This should be in Quotes!!
wc.hiddenSSID = true;
wc.status = WifiConfiguration.Status.ENABLED;
wc.priority = 40;
wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wc.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
wc.preSharedKey = "\"" + deviceConfig.wireless_passkey + "\"";//
Log.d("ssid : ", wc.SSID );
List<WifiConfiguration> netWorkList = wifi.getConfiguredNetworks();
WifiConfiguration wifiCong = null;
if (netWorkList != null) {
for(WifiConfiguration item:netWorkList) {
if (item.SSID.equalsIgnoreCase("\"" + deviceConfig.wireless_ssid + "\"")) {
wifiCong = item;
}
}
}
if (wifiCong == null) {
boolean res1 = wifi.setWifiEnabled(true);
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 es = wifi.saveConfiguration();
Log.d("WifiPreference", "saveConfiguration returned " + es );
}
}
Thanks
Kiran
I had this problem as well. The way I solved it was manually adding the wifi network to the device. I then enumerated over the configuration and copied the values that the device added to successfully connect to that network.
To clarify:
Add the network by hand, call the network manager to get the configured networks, find your network, and then call the getters out of everything you are trying to set - you will find the exact configuration you need.
void getWifiConfigs()
{
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
List<WifiConfiguration> networks = wifi.getConfiguredNetworks();
for (WifiConfiguration current : networks){
//check getters here
}
}