【问题标题】:Checking for Internet connectivity on Android [duplicate]在 Android 上检查 Internet 连接 [重复]
【发布时间】:2016-09-01 06:53:32
【问题描述】:

我写了下面的代码来检查互联网连接

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错误,为什么?

【问题讨论】:

  • 您是否在清单文件中添加了互联网权限?
  • 您是否在 AndroidManifest 文件中授予权限?
  • 异常消息说您尝试调用方法isConnectedOrConnecting(),而在您的代码中只有isConnected() 调用。你确定你展示的是正确的代码片段吗?
  • 试试这个解决方案吧stackoverflow.com/questions/37593058/…
  • @lawstud,我已经添加了互联网权限

标签: android internet-connection


【解决方案1】:

使用此代码:

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

【讨论】:

    猜你喜欢
    • 2013-03-15
    • 1970-01-01
    • 1970-01-01
    • 2012-11-24
    • 1970-01-01
    • 1970-01-01
    • 2014-08-18
    • 2020-11-07
    • 1970-01-01
    相关资源
    最近更新 更多