为什么应用程序无法启动此代码?

时间:2013-03-08 21:36:25

标签: android connection

所以我在这里找到了this answer。 但是我无法运行它,因为在使用Context类型参数调用isNetworkAvailable函数时没有定义它。 这是我使用的代码:

private boolean isNetworkAvailable(Context context)
{
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = cm.getActiveNetworkInfo();
    if(ni!= null && ni.isConnected())
    {
        return true;
    }
    return false;
}
public boolean dostupanInternet(Context context)
{
    if(isNetworkAvailable(context))
    {
        try
        {
            HttpURLConnection url = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
            url.setRequestProperty("User-Agent", "test");
            url.setRequestProperty("Connection", "close");
            url.setConnectTimeout(1000);
            url.connect();
            return(url.getResponseCode() == 200);
        }
        catch(IOException e)
        {
            Log.e("LOG_TAG","Povezivanje sa internetom nije uspelo",e);
        }
    }
    else
        {
            Log.d("LOG_TAG", "Povezivanje sa internetom nije uspelo");
        }
    return false;
}

但是当我运行它时会返回致命错误并强制应用程序关闭。 所以我的问题是 - 导致致命错误的原因(显然是未处理的异常)以及什么代码会让我通过互联网可用性检查?

1 个答案:

答案 0 :(得分:0)

尝试使用此方法

public boolean isConnectingToInternet(Context context){
    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;
}