Android真正的网络连接状态

时间:2013-01-31 07:44:33

标签: android android-networking

如何了解设备的真实连接状态。在我的应用程序中,我注册了ConnectivityManager.CONNECTIVITY_ACTION意图。我收到意图,他们说,设备上有连接:

ConnectivityManager.EXTRA_NO_CONNECTIVITY from intent == false

NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
ni.isAvailable() == true
ni.isConnected() == true

这是正确的,例如,设备连接到wifi点并且信号强度正常,但是应用程序无法连接到服务器,因为互联网访问目前在提供商端被破坏。看起来设备已经知道这个问题,因为它在状态栏上显示为灰色的wifi图标。

如何了解互联网连接的真实状态?

3 个答案:

答案 0 :(得分:0)

您可以使用它来确定您是否已连接:

final ConnectivityManager connectManager = (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);

final NetworkInfo mobile = connectManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
final NetworkInfo wifi   = connectManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI  );

// Return true if connected, either in 3G or wi-fi
return ((mobile != null && mobile.getState() == NetworkInfo.State.CONNECTED) || 
        (wifi   != null && wifi.getState()   == NetworkInfo.State.CONNECTED)   );
}

答案 1 :(得分:0)

您可以使用以下代码检查设备的互联网连接。我希望它会对你有所帮助。

 public static boolean IsNetConnected(Context mContext)
{
    boolean NetConnected = false;
    try
    {
        ConnectivityManager connectivity =
                (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null)
        {
            NetConnected = false;
        }
        else
        {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
            {
                for (int i = 0; i < info.length; i++)
                {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED)
                    {
                        NetConnected = true;
                    }
                }
            }
        }
    }
    catch (Exception e)
    {
        NetConnected = false;
    }
    return NetConnected;
}

答案 2 :(得分:0)

你是对的。这不是一种100%准确的方法来检测您的连接状态,但您可以尝试

public static boolean hasActiveInternetConnection(Context context) {
    if (isNetworkAvailable(context)) {
        try {
            HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
            urlc.setRequestProperty("User-Agent", "Test");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1500); 
            urlc.connect();
            return (urlc.getResponseCode() == 200);
        } catch (IOException e) {
            Log.e(LOG_TAG, "Error checking internet connection", e);
        }
    } else {
        Log.d(LOG_TAG, "No network available!");
    }
    return false;
}

请注意,Google可能会在某些国家/地区受到限制