Skip to content

Instantly share code, notes, and snippets.

@sdecima
Created December 18, 2013 17:46
Show Gist options
  • Save sdecima/8026686 to your computer and use it in GitHub Desktop.
Save sdecima/8026686 to your computer and use it in GitHub Desktop.
How to get Network information on Android and detect if it's connected or not. Detect if Mobile or Wifi (or any other connection type) is currently connected.
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class Android_getNetworkInfo {
public static boolean isNetworkConnectedOrConnecting(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
return (activeNetworkInfo != null &&
activeNetworkInfo.isConnectedOrConnecting());
}
public static boolean isNetworkConnectedOrConnectingMobile(Context context, int connectivityType) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
return (activeNetworkInfo != null &&
activeNetworkInfo.isConnectedOrConnecting() &&
activeNetworkInfo.getType() == connectivityType);
}
public void usage(Context context) {
boolean isConnected = isNetworkConnectedOrConnecting(context);
boolean isMobileConnected = isNetworkConnectedOrConnectingMobile(context, ConnectivityManager.TYPE_MOBILE);
boolean isWifiConnected = isNetworkConnectedOrConnectingMobile(context, ConnectivityManager.TYPE_WIFI);
boolean isEthernetConnected = isNetworkConnectedOrConnectingMobile(context, ConnectivityManager.TYPE_ETHERNET);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment