Skip to content

Instantly share code, notes, and snippets.

@dgmltn
Last active January 1, 2016 11:29
Show Gist options
  • Save dgmltn/8138732 to your computer and use it in GitHub Desktop.
Save dgmltn/8138732 to your computer and use it in GitHub Desktop.
The proper way to determine network connectivity in Android.
/**
* This static method determines if we have network connectivity at this moment.
* @param context the app context
* @return true if network is up and available, false otherwise
*/
public static boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return (ni != null && ni.isAvailable() && ni.isConnected());
}
// Not necessary, but to trigger an event when network status changes,
// include the following in your Activity / Fragment
@Override
public void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mConnReceiver, filter);
}
@Override
public void onPause() {
super.onPause();
unregisterReceiver(mConnReceiver);
}
private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (isOnline(context)) {
//TODO
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment