Reputation: 309
From my application, I am able to switch on/off WIFI in my device and able to scan the available networks, but i am unable to connect to specified available network. This is the code I am using:
if(wifi.getWifiState()==wifi.WIFI_STATE_DISABLED)
{
wifi.setWifiEnabled(true);
}
if(wifi.startScan())
{
//ls=(ArrayAdapter<ScanResult>) wifi.getScanResults();
ls=wifi.getScanResults();
Log.e("",ls.get(0).toString());
for(int i=0;i<ls.size();i++)
{ Log.e("VALUE"," "+ls.get(i).toString());
Log.e("",""+ls.get(i).SSID);
if(ls.get(i).SSID.equalsIgnoreCase("SPECTRUM-GREEN"))
{
Log.e("","SPectrum GREEN FOUND.....");
try{
String ssid="\""+ls.get(i).SSID+"\"";
Log.e("SSId"," "+ssid);
config.SSID=ssid;
}catch(Exception e){Log.e("","Error : "+e.toString());}
config.preSharedKey="\"password\"";
config.status=WifiConfiguration.Status.ENABLED;
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
int res=wifi.addNetwork(config);
Log.e("ENABLE ",""+wifi.enableNetwork(res, false));
break;
}
}
Upvotes: 2
Views: 2779
Reputation: 11926
Although this is an old question, in case someone comes across this, the following helped me:
void connect (String ssidName) {
boolean result = false;
List<WifiConfiguration> arraylist = wifiManager.getConfiguredNetworks();
for (WifiConfiguration wifiConfiguration : arraylist) {
String wifiConfigSSID = wifiConfiguration.SSID.replace("\"", "");
if (wifiConfigSSID.equals(ssidName)) {
result = wifiManager.enableNetwork(wifiConfiguration.networkId, true);
break;
}
}
}
If the network is already available, then there is no need for giving the various parameters, including the password.
Upvotes: 1
Reputation: 6159
You have to disable other networks:
wifi.enableNetwork(res, true);
Upvotes: 0
Reputation: 11053
Just a comment. Are you trying to connect ad hoc? This is not possible with "normal" Android phones I read...
Upvotes: 0