ahmad
11/24/2016 - 9:15 AM

Network connectivity receiver for android. Notifies you whenever network is connected or disconnected

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);
        }
    }
};