ConnectivityManager to verify internet connection

2019-08-04 15:38发布

问题:

Hi all I need to verify if my device is currently connected to internet or not and so I wrote this class that uses a ConnectivityManager to check:

public boolean checkInternetConnection() {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected()) {
        return true;

    } else {
        return false;
    }
}

works great, because right now the method is in a class in the main package (com.App), but how should I change the code to make it work in a class defined in com.App.Utility ?

Thanks!

回答1:

package com.app.utility;

  public class Utilities {

    public static final boolean CheckInternetConnection(Context context) {
      ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

      if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected()) {
        return true;

      } else {
        return false;
      }
    }
  }


回答2:

The only issue with using getActiveNetworkInfo() is that there are a number of situations where is will not correctly detect connectivity. For example if the mobile network is disabled on a phone but wifi is available then the active network may still be counted as the mobile network and therefore return false.

An alternative is:

public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfoMob = cm.getNetworkInfo(cm.TYPE_MOBILE);
    NetworkInfo netInfoWifi = cm.getNetworkInfo(cm.TYPE_WIFI);
    if ((netInfoMob != null || netInfoWifi != null) && (netInfoMob.isConnectedOrConnecting() || netInfoWifi.isConnectedOrConnecting())) {
        return true;
    }
    return false;
}


回答3:

Thx Alan H!

The if condition may cause NPE when one of netInfoMob and netInfoWifi is null but the other not.

This one works for me:

netInfoMobile != null && netInfoMobile.isConnectedOrConnecting() ||
netInfoWifi != null && netInfoWifi.isConnectedOrConnecting()


回答4:

Try this , this code works.

public static boolean checkNetwork(Context context) {
   context = context;
    ConnectivityManager connManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if ((connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) != null && connManager
            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected())
            || (connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI) != null && connManager
            .getNetworkInfo(ConnectivityManager.TYPE_WIFI)
            .isConnected())) {
        return true;
    } else {
        return false;
    }
}