Created
December 18, 2013 17:46
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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