I don't want my user to even try downloading something unless they have Wi-Fi connected. However, I can only seem to be able to tell if Wi-Fi is enabled, but they could still have a 3G connection.
android.net.wifi.WifiManager m = (WifiManager) getSystemService(WIFI_SERVICE);
android.net.wifi.SupplicantState s = m.getConnectionInfo().getSupplicantState();
NetworkInfo.DetailedState state = WifiInfo.getDetailedStateOf(s);
if (state != NetworkInfo.DetailedState.CONNECTED) {
return false;
}
However, the state is not what I would expect. Even though Wi-Fi is connected, I am getting OBTAINING_IPADDR
as the state.
I am using this in my apps to check if the active network is Wi-Fi:
This works for me:
And add this permission:
Try
This returns 0 until the device has a usable connection (on my machine, a Samsung SM-T280, Android 5.1.1).
You should be able to use the ConnectivityManager to get the state of the Wi-Fi adapter. From there you can check if it is connected or even available.
NOTE: It should be noted (for us n00bies here) that you need to add
to your
AndroidManifest.xml for this to work.
NOTE2:
public NetworkInfo getNetworkInfo (int networkType)
is now deprecated:NOTE3:
public static final int TYPE_WIFI
is now deprecated:Since the method NetworkInfo.isConnected() is now deprecated in API-23, here is a method which detects if the Wi-Fi adapter is on and also connected to an access point using WifiManager instead: