Skip to content

Instantly share code, notes, and snippets.

@andhikayuana
Created December 11, 2017 10:22
Show Gist options
  • Save andhikayuana/fe2bf9db4c3f0f7e02e1039484d9844e to your computer and use it in GitHub Desktop.
Save andhikayuana/fe2bf9db4c3f0f7e02e1039484d9844e to your computer and use it in GitHub Desktop.
Network Detector
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
/**
* @author yuana <[email protected]>
* @since 12/11/17
*/
public class NetworkUtil {
public static final String NETWORK_WIFI = "wifi_network";
public static final String NETWORK_4G = "4g_network";
public static final String NETWORK_3G = "3g_network";
public static final String NETWORK_2G = "2g_network";
public static final String NETWORK_UNKNOWN = "unknown_network";
public static final String NETWORK_NO = "no_network";
public static NetworkInfo getNetworkInfo(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo();
}
public static boolean isConnected(Context context) {
NetworkInfo info = getNetworkInfo(context);
return (info != null && info.isConnected());
}
public static boolean isConnectedWifi(Context context) {
NetworkInfo info = getNetworkInfo(context);
return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI);
}
public static boolean isConnectedMobile(Context context) {
NetworkInfo info = getNetworkInfo(context);
return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_MOBILE);
}
public static String getNetworkType(Context context) {
if (isConnected(context)) {
if (isConnectedWifi(context)) {
return NETWORK_WIFI;
} else if (isConnectedMobile(context)) {
switch (getType(context)) {
case TelephonyManager.NETWORK_TYPE_GPRS:
case TelephonyManager.NETWORK_TYPE_EDGE:
case TelephonyManager.NETWORK_TYPE_CDMA:
case TelephonyManager.NETWORK_TYPE_1xRTT:
case TelephonyManager.NETWORK_TYPE_IDEN:
return NETWORK_2G;
case TelephonyManager.NETWORK_TYPE_UMTS:
case TelephonyManager.NETWORK_TYPE_EVDO_0:
case TelephonyManager.NETWORK_TYPE_EVDO_A:
case TelephonyManager.NETWORK_TYPE_HSDPA:
case TelephonyManager.NETWORK_TYPE_HSUPA:
case TelephonyManager.NETWORK_TYPE_HSPA:
case TelephonyManager.NETWORK_TYPE_EVDO_B:
case TelephonyManager.NETWORK_TYPE_EHRPD:
case TelephonyManager.NETWORK_TYPE_HSPAP:
return NETWORK_3G;
case TelephonyManager.NETWORK_TYPE_LTE:
return NETWORK_4G;
default:
return NETWORK_UNKNOWN;
}
}
} else {
return NETWORK_NO;
}
return NETWORK_UNKNOWN;
}
private static int getType(Context context) {
TelephonyManager mTelephonyManager = (TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE);
return mTelephonyManager.getNetworkType();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment