Last active
January 1, 2016 11:29
-
-
Save dgmltn/8138732 to your computer and use it in GitHub Desktop.
The proper way to determine network connectivity in Android.
This file contains hidden or 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
/** | |
* 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