Reputation: 581
I want to send data over local network using wifi. Before sending data I check the wifi state, and, if it not enabled, ask the user and turn wifi on. The problem is if I turn wifi on and try to use it immediately, I have got an error cause the wifi need some time to be turned on.
So, as I think, I need to turn wifi on and set the handler which will be called when wifi goes to enabled state. But WifiManager doesn't provide such methods with handlers. How I can catch changing of wifi state?
UPD
How I turn wifi on:
WifiManager wifi = WifiUtils.getWifi( getApplicationContext() );
if (WifiUtils.isWifiEnabled( wifi)) return true;
wifi.setWifiEnabled(true);
//---
public static WifiManager getWifi( Context ctx)
{
return (WifiManager)ctx.getSystemService(ctx.WIFI_SERVICE);
}
public static boolean isWifiEnabled( WifiManager wifi)
{
if (wifi==null) return false;
if (wifi.getWifiState()!=wifi.WIFI_STATE_ENABLED) return false;
return true;
}
Upvotes: 0
Views: 3204
Reputation: 5591
First of all if you want to check if wifi is connected or not You can use this
ConnectivityManager cm = (ConnectivityManager) getSystemService(
Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifiNetwork != null && wifiNetwork.isConnected()) {
}
else{
//ask your user to turn on wifi
}
Now if you want to check whether the device can access internet even if wifi is on, then you could do something like
if (wifiNetwork != null && wifiNetwork.isConnected()) {
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(10000);
int responseCode = conn.getResponseCode();
if(responseCode == 200){
//internet access
}
else {
//no internet access
}
}
If you want to handle wifi state changes then you can try BroadcastReceiver when wifi or 3g network state changed or Android: Getting Notified of Connectivity Changes
However if you want to turn wifi on programmatically refer this SO question.Basically you will need to do something like this
WifiManager wManager = (WifiManager)this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wManager.setWifiEnabled(booleanValue); //true for on and false for off
And of course you will need to add necessary permissions in your AndroidManifest.xml
like
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.UPDATE_DEVICE_STATS"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
Upvotes: 2