I am new to android development and was trying to connect to WiFi network using the Android SDK. The code for disconnect works fine but re-connection fails. Here's the code that i have
try {
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + networkSSID + "\""; // Please note the quotes. String should contain SSID in quotes
conf.wepKeys[0] = password; //WEP password is in hex, we do not need to surround it with quotes.
conf.wepTxKeyIndex = 0;
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
WifiManager wifiManager = (WifiManager)ba.applicationContext.getSystemService(Context.WIFI_SERVICE);
wifiManager.addNetwork(conf);
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for( WifiConfiguration i : list ) {
if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.reconnect();
break;
}
}
//WiFi Connection success, return true
return true;
} catch (Exception ex) {
throw ex;
}
I am wrapping this code in a jar file which I am using in different application. When I call this method and try to connect to WEP network using the SSID and password, I keep on getting the following error:
android.system.ErrNoException: recvfrom failed: ETIMEDOUT (Connection timed out).
The error does tell that there is a connection timeout somewhere, but I haven't been able to figure this out to fix my code. Any pointers and changes that I can introduce to code to make this work??
Paritosh
Connection information can arrive asynchronously, so you cannot know in the code you mentioned wether the connection was successful or not. You can try to implement a BroadcastReceiver, that gets the information of the wifi connection.
public class ConnectivityChangedReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInf = conMgr.getAllNetworkInfo();
for (NetworkInfo inf : netInf) {
if (inf.getTypeName().contains("wifi")) {
if (inf.isConnected()) {
Toast.makeText(context, "Connected to Wifi", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Could not connect to wifi", Toast.LENGTH_SHORT).show();
}
}
}
}
}
Then, in your android manifest you should declare it as beeing a receiver, like this:
<receiver android:name=".YourPackageName.ConnectivityChangedReceiver" >
<intent-filter>
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
<action android:name="android.net.wifi.STATE_CHANGE" />
</intent-filter>
</receiver>
I am just trying this on my own now, but I think that this is the correct workaround for this issue, as Wifimanager.reconnect() didn't really connected me to the configured network. Best of luck.
来源:https://stackoverflow.com/questions/29117522/cant-connect-to-wifi-network