Skip to content

Instantly share code, notes, and snippets.

@pratikbutani
Last active May 3, 2017 12:29
Show Gist options
  • Save pratikbutani/735ebb995a27caf53c2d64a717ecc98f to your computer and use it in GitHub Desktop.
Save pratikbutani/735ebb995a27caf53c2d64a717ecc98f to your computer and use it in GitHub Desktop.
NetworkUtils is useful to check the internet connection and it will be called when internet connection goes on/off using BroadcaseReceiver.
/**
* @author Pratik Butani
*/
public class NetworkUtils extends BroadcastReceiver {
/**
* Context Variable
*/
Context context;
/**
* Check whether Internet connection is available or not...
*/
boolean connected;
/**
* CHECK WHETHER INTERNET CONNECTION IS AVAILABLE OR NOT
*/
public static boolean checkConnection(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) { // connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI ||
activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
return true;
}
}
return false;
}
@Override
public void onReceive(final Context context, Intent intent) {
this.context = context;
connected = checkConnection(context);
if (connected) {
LOGD("Connection Available");
} else {
LOGD("Connection Unavailable");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment