Created
July 8, 2014 10:25
-
-
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
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
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