Checking internet connection in android using getActiveNetworkInfo

被刻印的时光 ゝ 提交于 2019-12-12 02:36:56

问题


if you want to check internet connection in android there is a lot of ways to do that for example:

   public boolean isConnectingToInternet(){
    ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
      if (connectivity != null) 
      {
          NetworkInfo[] info = connectivity.getAllNetworkInfo();
          if (info != null) 
              for (int i = 0; i < info.length; i++) 
                  if (info[i].getState() == NetworkInfo.State.CONNECTED)
                  {
                      return true;
                  }

      }
      return false;
    }

getAllNetworkInfo(); was deprecated in api level 23 so i need a solution to check internet connection both api level 23 and prior,i found another way to do that

 private boolean isConnectedToInternet()
{
    ConnectivityManager cm = (ConnectivityManager) SplashActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (activeNetwork != null) { // connected to the internet
            if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
                // connected to wifi
                Toast.makeText(SplashActivity.this, activeNetwork.getTypeName(), Toast.LENGTH_SHORT).show();
                return true;
            } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
                // connected to the mobile provider's data plan
                Toast.makeText(SplashActivity.this, activeNetwork.getTypeName(), Toast.LENGTH_SHORT).show();
                return true;
            }
        } 
    return false;
}

my question is about getActiveNetworkInfo() and isConnected() the documentation provided by google for this method is here

Returns details about the currently active default data network. When connected, this network is the default route for outgoing connections. You should always check isConnected() before initiating network traffic. This may return null when there is no default network.

why we need to call isConnected() on getActiveNetworkInfo() for checking internet connection while we can check returned value from getActiveNetworkInfo() with null if not null we have internet connection else if returned null calling isConnected() on getActiveNetworkInfo() throws null pointer exception at runtime?


回答1:


Use my util class:

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;

/**
 * Created by ozgur on 16.04.2016.
 */
public class Utils {

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

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {

            Network[] activeNetworks = cm.getAllNetworks();
            for (Network n: activeNetworks) {
                NetworkInfo nInfo = cm.getNetworkInfo(n);
                if(nInfo.isConnected())
                    return true;
            }

        } else {
            NetworkInfo[] info = cm.getAllNetworkInfo();
            if (info != null)
                for (NetworkInfo anInfo : info)
                    if (anInfo.getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
        }

        return false;

    }
}



回答2:


Network info in deprecated. Use network callback. This is the method.

public void registerNetworkCallback()
{
    try {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkRequest.Builder builder = new NetworkRequest.Builder();

        connectivityManager.registerNetworkCallback(builder.build(),new ConnectivityManager.NetworkCallback() {
                    @Override
                    public void onAvailable(Network network) {
                        Variables.isNetworkConnected = true; // Global Static Variable
                    }
                    @Override
                    public void onLost(Network network) {
                        Variables.isNetworkConnected = false; // Global Static Variable
                    }
                }

        );
        Variables.isNetworkConnected = false;
    }catch (Exception e){
        Variables.isNetworkConnected = false;
    }
}

Please check the full code here : Gist



来源:https://stackoverflow.com/questions/37507451/checking-internet-connection-in-android-using-getactivenetworkinfo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!