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
}
}
Related
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.
I need to connect to hidden Wi-Fi network programmatically.
I know it's SSID, security type and password.
For some reason I can't connect it.
I can connect to the same network if it's not hidden.
Here's my code:
// configure the network
private void saveWPANetwork(WiFiNetwork network){
WifiConfiguration conf = new WifiConfiguration();
conf.SSID =network.getSSID();
conf.hiddenSSID = true;
conf.status = WifiConfiguration.Status.ENABLED;
conf.preSharedKey =network.getPassword();
conf.priority = 9999;
wifi.addNetwork(conf);
wifi.saveConfiguration();
}
// connect it
protected boolean connectToVaildNetwork() {
List<WifiConfiguration> list = wifi.getConfiguredNetworks();
if(list == null)
return false;
for( WifiConfiguration i : list ) {
for (WiFiNetwork network : config.wiFiNetworksDetails) {
if(network.getSSID().equalsIgnoreCase(i.SSID)){
wifi.enableNetwork(i.networkId, true);
return wifi.reconnect(); /// STRANGE BUT IT ALWAYS RETURNS TRUE, EVEN IF DEVICE IS NOT CONNECTED TO THE HIDDEN NETWORK!
}
}
}
return false;
}
This answer maybe late but I still post it in case of someone need.
Android 4.4.2 tested. Notes that hidden networks take longer time to connect (for my test it was around 10-15s)
wifi.reconnect() == true means that your command has been requested successfully, it does not mean that wifi is connected.
public void setWifiConfig(String ssid, String sharedKey) {
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + ssid + "\""; // Please note the quotes. String should contain ssid in quotes
conf.preSharedKey = "\"" + sharedKey + "\"";
conf.hiddenSSID = true;
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.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
conf.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
wifiManager.addNetwork(conf);
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for (WifiConfiguration i : list) {
if (i.SSID != null && i.SSID.equals("\"" + ssid + "\"")) {
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.reconnect();
wifiManager.saveConfiguration();
break;
}
}
}
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'm going to create xposed module that will add one option to the window which appears when user clicks/holds one of WiFi networks. The dialog box where are located options like "connect", "modify", "cancel".
Where do I find these methods?
public void connectTowifi()
{
String ssid = ""// ssid of clicked network
String pass = "" // pass of clicked network
WifiConfiguration wifiConfig = new WifiConfiguration();
wifiConfig.SSID = "\"" ssid +"\"";
wifiConfig.preSharedKey = "\"" + OfflineUtils.generatePassword(ssid) + "\"";
wifiManager.addNetwork(wifiConfig);
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for( WifiConfiguration wifiConfiguration : list )
{
if(wifiConfiguration!=null && wifiConfiguration.SSID != null && wifiConfiguration.SSID.equals(wifiConfig.SSID))
{
wifiManager.disconnect();
wifiManager.enableNetwork(wifiConfiguration.networkId, true);
wifiManager.reconnect();
}
}
}
Similarly for diabling network use
http://developer.android.com/reference/android/net/wifi/WifiManager.html#disableNetwork(int)
for forgetiing network
http://developer.android.com/reference/android/net/wifi/WifiManager.html#removeNetwork(int)
for disconnect connection:
http://developer.android.com/reference/android/net/wifi/WifiManager.html#disconnect()
For updating netwrok
http://developer.android.com/reference/android/net/wifi/WifiManager.html#updateNetwork(android.net.wifi.WifiConfiguration)
For all other methods
refer to
http://developer.android.com/reference/android/net/wifi/WifiManager.html
I'm working on an Android app that connects to custom hardware via networking.
If you set it up to use a wireless access point, it works fine.
If you set it up to use an access point on the device (aka tethering), it works fine.
If you set it up to use an ad-hoc network, it doesn't work. Android fails at the "obtaining IP address" step.
our work-around was to use a static IP address, and low and behold it worked! If you connect the tablet to our custom hardware and force a custom subnet mask and IP address, it connects instantly.
However, that's too confusing. DHCP or GTFO. Our solution uses a custom network manager, and if it's an ad-hoc network force a static IP address automatically. This should work.
I've followed the directions at this link (with some modifications) and it works perfectly-ish. You can select the network, assign it a static IP address, and that's it. The android tablet will never connect to the network. However, if you look at the network under the "real" wifi manager and select "modify settings", you can see where all of the static IP address information is saved. It just won't connect.
Adding to my misery, if you remove the network, and go to the android wifi manager and enter the information in manually, it works. but not if you do the same steps programatically.
Does anyone know why this is, or how to fix it? This is on a rooted nexus 7.
Thanks in advance.
public void connectToWiFiNetwork(String networkSSID, String networkPass, String type)
{
//Make sure a password is set
if(networkPass != null && networkPass.length() == 0)
return;
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + networkSSID + "\""; // Please note the quotes. String should contain ssid in quotes
conf.status = WifiConfiguration.Status.ENABLED;
int id = -1;
if(type.contains("WPA")) {
conf.preSharedKey = "\""+ networkPass +"\"";
//conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
System.out.println("Contains WPA");
} else if (type.contains("WEP")) {
conf.wepKeys[0] = "\"" + networkPass + "\"";
conf.wepTxKeyIndex = 0;
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
System.out.println("Contains WEP");
} else {
//open network?
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
System.out.println("Open WiFi");
}
if(type.contains("IBSS"))
{
//Adhoc network. Provide an IP address to prevent... stuff.
//For Android 2.x
//final ContentResolver cr = this.context.getContentResolver();
//Settings.System.putInt(cr, Settings.System.WIFI_USE_STATIC_IP, 1);
//Settings.System.putString(cr, Settings.System.WIFI_STATIC_IP, "169.254.1.1");
//Settings.System.putString(cr, Settings.System.WIFI_STATIC_NETMASK, "255.255.0.0");
try{
//Some code here isn't used...
WifiConfiguration wifiConf = null;
WifiManager wifiManager = (WifiManager)this.context.getSystemService(Context.WIFI_SERVICE);
WifiInfo connectionInfo = wifiManager.getConnectionInfo();
List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks();
for (WifiConfiguration conf2 : configuredNetworks){
if (conf2.networkId == connectionInfo.getNetworkId()){
wifiConf = conf2;
break;
}
}
wifiConf = conf;
setIpAssignment("STATIC", wifiConf); //or "DHCP" for dynamic setting
Log.d("CONNECTION", "Connecting now using a static IP address");
setIpAddress(InetAddress.getByName("169.254.1.1"), 24, wifiConf);
Log.d("CONNECTION", "Connecting now using a static IP address");
setGateway(InetAddress.getByName("255.255.0.0"), wifiConf);
Log.d("CONNECTION", "Connecting now using a static IP address");
setDNS(InetAddress.getByName("8.8.8.8"), wifiConf);
Log.d("CONNECTION", "Connecting now using a static IP address");
//wifiManager.updateNetwork(wifiConf); //apply the setting
Log.d("CONNECTION", "Connecting now using a static IP address");
}catch(Exception e){
e.printStackTrace();
}
}
id = wifi.addNetwork(conf);
wifi.saveConfiguration();
//Add the network
//And enable it
List<WifiConfiguration> list = wifi.getConfiguredNetworks();
for( WifiConfiguration i : list ) {
if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
wifi.disconnect();
wifi.enableNetwork(i.networkId, true);
wifi.reconnect();
break;
}
}
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("auto_start_tethering", false);
editor.commit();
Log.d("CONNECTION", "Connecting using " + networkSSID + " and " + networkPass + ".");
}