0

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

ConnectivityManager.EXTRA_NO_CONNECTIVITY from intent == false

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

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

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

4

3 回答 3

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)   );
}
于 2013-01-31T07:47:52.687 回答
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;
}
于 2013-01-31T07:48:13.833 回答
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;
}

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

于 2013-01-31T07:52:46.873 回答