Note: requires android.Manifest.permission.ACCESS_NETWORK_STATE
in the manifest.
Neither of the methods below guarantee that the device can make requests - it might be connected to a WiFi spot that is not connected to the internet, for example.
Check if device is connected (wifi or data)
public static boolean isConnected(Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
}
Check for WiFi specifically
public static boolean isConnectedToWiFi(@NonNull Context context) {
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(
Context.CONNECTIVITY_SERVICE);
if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
for (Network network : manager.getAllNetworks()) {
final NetworkInfo info = manager.getNetworkInfo(network);
if ((info.isConnected() || info.isConnectedOrConnecting())
&& info.getType() == ConnectivityManager.TYPE_WIFI) {
return true;
}
}
return false;
} else {
NetworkInfo wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return wifi != null && wifi.isConnected();
}
}