检查Android上的Internet连接

时间:2016-09-01 06:53:33

标签: android internet-connection

我编写了以下代码来检查互联网连接

public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager cm =
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork == null) {
        return false;
    } else {
        if (activeNetwork.isConnected()) {
          return true;
        }
    }
}

我检查activeNetWork是否为null,但仍然出现NullPointerException错误,为什么? enter image description here

1 个答案:

答案 0 :(得分:0)

使用此代码:

public static boolean isInternetconnected(Context ct) {  
   boolean connected = false;  
   //get the connectivity manager object to identify the network state.  
   ConnectivityManager connectivityManager = (ConnectivityManager)ct.getSystemService(Context.CONNECTIVITY_SERVICE);  
  //Check if the manager object is NULL, this check is required. to prevent crashes in few devices.
  if(connectivityManager != null) {  
     //Check Mobile data or Wifi net is present  

      if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||   
               connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED)  {  
    //we are connected to a network  
    connected = true;  
     } else {  
      connected = false;  
   }  
  return connected;  
  } else  {  
  return false;  
 }  
}