7

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

Ritika
  • 101
  • 1
  • 4
  • Maybe you should extend WakefulBroadcastReceiver – Gavriel Jan 19 '16 at 18:42
  • 1
    It seems BLOCKED could mean powered down to save battery. I tried a network request in this state and it DID go through but with a longer delay than normal. – paul Jun 06 '17 at 23:13
  • I've got the same problem and found an issue on Google's issue tracker that seems to fit: https://issuetracker.google.com/issues/37137911 As a quick-fix I used a similar fallback-solution as mentioned in https://stackoverflow.com/a/45231746/1394330 – th3hamm0r Oct 12 '17 at 13:31

3 Answers3

5

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.

Phil
  • 1,200
  • 13
  • 17
  • Running into the same issue on Nexus 6p and Samsung S8 with power saver mode ON. Interestingly, Samsung S8 remains in power saver even while charging NetworkInfo from ConnectivityManager.EXTRA_NETWORK_INFO correctly says CONNECTED, but it is deprecated since API 16. I am not sure about using that. – Arun Anjay Anantha Aug 11 '17 at 16:37
  • 1
    In the example above is for backward compatibility the string is the same for WifiManager "networkInfo". – Phil Aug 16 '17 at 15:13
  • ConnectivityManager.EXTRA_NETWORK_INFO - It is deprecated as of API 16. – pravingaikwad07 Apr 05 '18 at 07:15
1

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! :)

David Jarvis
  • 2,769
  • 2
  • 15
  • 26
0
    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.

Sanf0rd
  • 3,644
  • 2
  • 20
  • 29