0

我对 Android 如何检查互联网连接感兴趣。例如,在我们公司的 wifi 中,wlan-symbol 变为灰色,即使有 http/https/dns 等可用的连接。在家(对防火墙没有限制)它变为蓝色。

哪些检查是在后台进行的?有人详细了解吗?

4

3 回答 3

0
public final boolean isInternetOn() {

    ConnectivityManager connec =  (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

    if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED ||
            connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTING ||
            connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING ||
            connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED ) 
    {
        return true;
    } else if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED ||  
            connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED  ) 
    {

        return false;
    }
    return false;
}//end of the Internet Connection Checking
于 2013-02-18T12:42:15.983 回答
0
private boolean isNetworkConnected() {
   ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
     NetworkInfo ni = cm.getActiveNetworkInfo();
  if (ni == null) {
  // There are no active networks.

返回假;} 否则返回真;}

       <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
于 2013-02-18T12:42:20.617 回答
0

您可以使用此功能检查应用程序中的网络:

  public boolean isConnectToInternet() {
        ConnectivityManager connectivity = (ConnectivityManager) 
        getApplicationContext().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;
      }

您必须在 manifest.xml 中添加此权限:

  <uses-permission android:name="android.permission.INTERNET"/>
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
于 2019-07-06T13:42:35.157 回答