在Android中检查互联网访问时,为什么总是返回" true"?

时间:2014-07-08 18:03:55

标签: android

如何在Android中检查互联网访问权限?

为什么总是返回true

我确信我没有连接到互联网。为什么返回true

public static boolean isOnline(Context context) {
    ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    // test for connection
    if (cm.getActiveNetworkInfo() != null &&
        cm.getActiveNetworkInfo().isAvailable() &&
        cm.getActiveNetworkInfo().isConnected()) {

        return true;
    } else {
        Log.v("TAG", "Internet Connection Not Present");
        return false;
    }
}

3 个答案:

答案 0 :(得分:3)

您可以尝试测试以确定哪个连接被视为活动:

public boolean isOnline() {
  ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
  NetworkInfo netInfoMob = cm.getNetworkInfo(cm.TYPE_MOBILE);
  NetworkInfo netInfoWifi = cm.getNetworkInfo(cm.TYPE_WIFI);
  if (netInfoMobile != null && netInfoMobile.isConnectedOrConnecting()) {
    Log.v("TAG", "Mobile Internet connected");
    return true;
  } 
  if (netInfoWifi != null && netInfoWifi.isConnectedOrConnecting()) {
    Log.v("TAG", "Wifi Internet connected");
    return true;
  } 
  return false;
}

编辑:在模拟器上,无论计算机的Internet连接如何,它都将始终显示移动连接。根据以下答案,使用F8将其关闭:

https://stackoverflow.com/a/2937915/560092

答案 1 :(得分:0)

public boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager 
              = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        boolean isAvailable = activeNetworkInfo != null && activeNetworkInfo.isConnected();
        if(!isAvailable) {
            Toast.makeText(this,"Unable to connect", Toast.LENGTH_SHORT).show();
        }
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

答案 2 :(得分:0)

您使用的方法始终无法正常工作。有时候,即使你连接到wifi网络(但网络实际上并没有连接到互联网),它也会返回真实状态。另一种选择是

public boolean isOnline() {
  ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
  NetworkInfo netInfoMob = cm.getNetworkInfo(cm.TYPE_MOBILE);
  NetworkInfo netInfoWifi = cm.getNetworkInfo(cm.TYPE_WIFI);
  if ((netInfoMobile != null && netInfoMobile.isConnectedOrConnecting()) || (netInfoWifi != null && netInfoWifi.isConnectedOrConnecting())) {
    return true;
}
  return false;
}