Skip to content

Instantly share code, notes, and snippets.

@Antarix
Created July 8, 2014 10:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Antarix/6108ccbbf1cd765de954 to your computer and use it in GitHub Desktop.
Save Antarix/6108ccbbf1cd765de954 to your computer and use it in GitHub Desktop.
Network connectivity receiver for android. Notifies you whenever network is connected or disconnected
private class ConnectivityBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)
|| mListening == false) {
Log.w(TAG, "onReceived() called with " + mState.toString()
+ " and " + intent);
return;
}
boolean noConnectivity = intent.getBooleanExtra(
ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
if (noConnectivity) {
mState = State.NOT_CONNECTED;
} else {
mState = State.CONNECTED;
}
mNetworkInfo = (NetworkInfo) intent
.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
mOtherNetworkInfo = (NetworkInfo) intent
.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
mReason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
mIsFailover = intent.getBooleanExtra(
ConnectivityManager.EXTRA_IS_FAILOVER, false);
if (DBG) {
Log.d(TAG,
"onReceive(): mNetworkInfo="
+ mNetworkInfo
+ " mOtherNetworkInfo = "
+ (mOtherNetworkInfo == null ? "[none]"
: mOtherNetworkInfo + " noConn="
+ noConnectivity) + " mState="
+ mState.toString());
}
// Notifiy any handlers.
Iterator<Handler> it = mHandlers.keySet().iterator();
while (it.hasNext()) {
Handler target = it.next();
Message message = Message.obtain(target, mHandlers.get(target));
// TODO add extra data
target.sendMessage(message);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment