Android: Checking network connectivity return not connected when connected to wifi/3g in Broadcast receiver

This is how I’m handling it as it turns out getActiveNetworkInfo will always return you DISCONNECTED/BLOCKED in a specific case even if there is network connection. This is the receive method in the BroadcastReceiver with intent filter ConnectivityManager.CONNECTIVITY_ACTION.

@Override
public void onReceive(Context context, Intent intent) {
    ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = conn.getActiveNetworkInfo();

    NetworkInfo intentNetworkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);

    if (intentNetworkInfo == null) {
        intentNetworkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
    }

    if (networkInfo == null) {
        networkInfo = intentNetworkInfo;
    } else {
        //when low battery get ActiveNetwork might receive DISCONNECTED/BLOCKED but the intent data is actually CONNECTED/CONNECTED
        if (intentNetworkInfo != null && networkInfo.isConnectedOrConnecting() != intentNetworkInfo.isConnectedOrConnecting()) {
            networkInfo = intentNetworkInfo;
        }
    }

    //do something with networkInfo object
}

I’ve searched for better solution but no results. The case I’ve been able to reproduce 100% on my device (Pixel 7.1.2) is the following:

  • The device must be on low battery < 15% (other devices <20%)
  • Wifi is on, app is launched
  • Send app to background turnoff wifi and go to 3g (or vice versa)
  • Go back to the app
  • In that situation the app will report DISCONNECTED/BLOCKED from getActiveNetworkInfo.

If you change connectivity while in app it will be ok but if it is on background it wont. This won’t happen while you are debugging because it will be charging the device even if the battery is low.

In the example above EXTRA_NETWORK_INFO in ConnectivityManager and WifiManager is actually same string “networkInfo” but I didn’t wan’t to risk it if in other Android versions they are different, so it is extra boilerplate.

You can directly use the networkInfo from the intent but I wanted to show here that there is a case where actualNetworkInfo is not the actual network info.

Leave a Comment