简体   繁体   中英

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

I want to check if device in connected or not in broadcastReceiver. below is my code :

public boolean isOnline(Context context) {
NetworkInfo info = (NetworkInfo) ((ConnectivityManager) context
        .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

if (info == null || !info.isConnected()) {
    Log.e("UpdateDataReceiver","info: "+info);
    return false;
}
return true;
}

Issue with my code: above function returns me false (even when wifi connected) when BroadcastReceiver fires in background(when app is in background) and it returns true when app is in foreground.

info: NetworkInfo: type: WIFI[], state: DISCONNECTED/BLOCKED, reason: (unspecified), extra: (none), roaming: false, failover: false, isAvailable: true, isConnectedToProvisioningNetwork: false, simId: 0

Device Info: Redmi Note

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.

I believe the way you can do this is,

Register a Broadcast Receiver with an IntentFilter of ConnectivityManger.Connectivity_Action

private BroadcastReceiver receiverDataChange;

private void registerData(){

    try {
        receiverDataChange = new bcr_ToggleData();
        IntentFilter filterData = new IntentFilter();
        filterData.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(receiverDataChange, filterData);

    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    }}

Then in your Broadcast receiver class

public class bcr_ToggleData extends BroadcastReceiver {


@Override
public void onReceive(Context context, Intent intent) {

    String action = intent.getAction();

    if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {

        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        int state = telephonyManager.getDataState();
        switch (state){

            case TelephonyManager.DATA_DISCONNECTED: // off
                Log.d("DavidJ", "DISCONNECTED");
                break;

            case TelephonyManager.DATA_CONNECTED: // on
                Log.d("DavidJ", "CONNECTED");
                break;
        }
    }
}

}

This fires off when you go into your settings and turn on/off mobile data.

Hope this helps! :)

    ConnectivityManager cm =
        (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
                      activeNetwork.isConnectedOrConnecting();

I found this on this google tutorial: http://developer.android.com/intl/pt-br/training/monitoring-device-state/connectivity-monitoring.html . check it out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM