Skip to content

Instantly share code, notes, and snippets.

@RahulSDeshpande
Forked from nishantkp/Network.java
Created January 4, 2023 08:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RahulSDeshpande/c568b0a78e2128c1ffad9566bba03c67 to your computer and use it in GitHub Desktop.
Save RahulSDeshpande/c568b0a78e2128c1ffad9566bba03c67 to your computer and use it in GitHub Desktop.
Find out application is connected to WIFI or cellular
/**
* Get reference to the connectivity manager
*/
ConnectivityManager connectivityManager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
/**
* Find out whether device is connected to wifi or cellular at the moment
*/
public NetworkType getNetworkType() {
boolean isConnectedToWifi;
boolean isConnectedToCellular;
if (connectivityManager == null) {
Log.e(TAG, "Connectivity manager not found!");
return NetworkType.ERROR;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Network activeNetwork = connectivityManager.getActiveNetwork();
if (activeNetwork == null) {
Log.e(TAG, "Active network not found for API >= 23");
return NetworkType.ERROR;
} else {
NetworkCapabilities nc = connectivityManager.getNetworkCapabilities(activeNetwork);
if (nc == null) {
Log.e(TAG, "Network capabilities not found for API >= 23");
return NetworkType.ERROR;
} else {
isConnectedToCellular = nc.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR);
isConnectedToWifi = nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI);
}
}
} else {
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null) {
if (networkInfo.isConnectedOrConnecting()) {
isConnectedToCellular =
networkInfo.getType() == ConnectivityManager.TYPE_MOBILE;
isConnectedToWifi =
networkInfo.getType() == ConnectivityManager.TYPE_WIFI;
} else {
Log.e(TAG, "Active network not found for API < 23");
return NetworkType.NO_NETWORK;
}
} else {
Log.e(TAG, "NetworkInfo not found for API < 23");
return NetworkType.ERROR;
}
}
if (isConnectedToCellular && isConnectedToWifi) {
return NetworkType.WIFI;
} else if (isConnectedToCellular) {
return NetworkType.CELLULAR;
} else if (isConnectedToWifi) {
return NetworkType.WIFI;
} else {
return NetworkType.NO_NETWORK;
}
}
/**
* Enum which specifies the type of network
*/
public enum NetworkType {
WIFI, /* wifi network */
CELLULAR, /* cellular network */
NO_NETWORK, /* no network */
ERROR /* error while figuring out the network type */
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment