使用getActiveNetworkInfo检查android中的Internet连接

时间:2016-05-29 07:45:51

标签: android internet-connection

如果你想检查 android 中的互联网连接,有很多方法可以做到这一点 例如:

   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(); 在api级别23中已弃用,所以我需要一个解决方案来检查api级别23和之前的互联网连接,我找到另一种方法来做到这一点

 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;
}

我的问题是关于getActiveNetworkInfo()和isConnected()google为此方法提供的文档是here

  

返回有关当前活动的默认数据网络的详细信息。连接时,此网络是传出连接的默认路由。在启动网络流量之前,您应该始终检查isConnected()。当没有默认网络时,这可能会返回null。

为什么我们需要在 getActiveNetworkInfo()上调用 isConnected()来检查互联网连接,同时我们可以使用 null检查来自getActiveNetworkInfo()的返回值如果不为null我们有互联网连接否则如果返回null调用isConnected()on getActiveNetworkInfo()在运行时抛出空指针异常

2 个答案:

答案 0 :(得分:4)

使用我的util类:

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;

    }
}

答案 1 :(得分:0)

不推荐使用网络信息。使用网络回调。这是方法。

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;
    }
}

请在此处检查完整代码:Gist