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.
Using
WifiManager
you can do:The method getNeworkId returns -1 only when it's not connected to a network;
You can turn WIFI on if it's not activated as the following 1. check WIFI state as answered by @Jason Knight 2. if not activated, activate it don't forget to add WIFI permission in the manifest file
Your Java class should be like that
}
In new version Android
and add premission too
I simply use the following:
Which will return one of these states at the time you call getSupplicantState();
This is an easier solution. See Stack Overflow question Checking Wi-Fi enabled or not on Android.
P.S. Do not forget to add the code to the manifest.xml file to allow permission. As shown below.
Here is what I use as a utility method in my apps: