Reputation: 7937
Here is how I check if the Android device is connected to a Wi-Fi network:
NetworkInfo info = ((ConnectivityManager) ctx.getSystemService(Context
.CONNECTIVITY_SERVICE)).getNetworkInfo(ConnectivityManager.TYPE_WIFI);
boolean isWifiConnected = info != null && info.isAvailable() && info.isConnected();
This works perfectly on all versions prior to Android 6.0. However, on Android 6.0, if the device is connected to a Wi-Fi without Internet access, info.isConnected() returns false.
So, how can I know for sure that the device is connected to a Wi-Fi on Android 6.0?
Upvotes: 4
Views: 2544
Reputation: 7937
For Android 5.0 and above you need to use a different API to check that the device is connected to a WiFi network. The device might also be simultaneously connected to a mobile network.
ConnectivityManager connectivityManager = ((ConnectivityManager) ctx.getSystemService
(Context.CONNECTIVITY_SERVICE));
boolean isWifiConnected = false;
Network[] networks = connectivityManager.getAllNetworks();
if (networks == null) {
isWifiConnected = false;
} else {
for (Network network : networks) {
NetworkInfo info = connectivityManager.getNetworkInfo(network);
if (info != null && info.getType() == ConnectivityManager.TYPE_WIFI) {
if (info.isAvailable() && info.isConnected()) {
isWifiConnected = true;
break;
}
}
}
}
return isWifiConnected;
Upvotes: 3
Reputation: 709
I have the same issue. You can check if there is an SSID, which implies a connection:
WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (wifiManager.getConnectionInfo() != null) {
String ssid = wifiManager.getConnectionInfo().getSSID();
}
The system is routing traffic to the cell connection, so the OS is reporting the Wi-Fi network as disconnected. Android 6.0 changed the underlying routing logic to avoid Wi-Fi connections without internet. This is why connectivityManager.getActiveNetworkInfo()
no longer returns the NetworkInfo
for the Wi-Fi connection w/o internet if there is an active cellular data connection.
It seems that ConnectivityManager.bindProcessToNetwork(Network network) is how you tell the OS to prefer one network over another.
Upvotes: 2