How to detect when WIFI is connected to internet?

二次信任 提交于 2019-12-21 21:58:02

问题


I am building an Android app and I use the code below to detect whether there is a network connection. It works well and detects both mobile and WIFI networks.

My problem is how to detect an actual internet connection. The code below returns true when connected to WIFI however the WIFI might not necessarily be connected to the Internet.

The code

    protected boolean checkInternetConnection() {     
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);  
    // test for connection     
    if (cm.getActiveNetworkInfo() != null             
            && cm.getActiveNetworkInfo().isAvailable()             
            && cm.getActiveNetworkInfo().isConnected()) {

        return true;

        } 
    else {               
        return false;

        } 

} //end checkInterneConnection method

Thanks for your time.

Mel


回答1:


You should try to reach an internet adress. Therefor you should check the InetAdress class and the method isReachable: http://developer.android.com/reference/java/net/InetAddress.html#isReachable%28int%29




回答2:


This piece of code will check whether your device Internet conecction, If the signal is Poor it will show a Toast other wise not,

ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo Info = conMan.getActiveNetworkInfo();

        if(Info == null){
            Toast.makeText(RegisterActivity.this,"Network Connection Failed! ", Toast.LENGTH_SHORT).show();
        }



回答3:


You can try ping http://google.com or doing something like this to confirm it's ok to visit internet.




回答4:


You should try this:

public boolean isConnectingToInternet(){
    ConnectivityManager connectivity = (ConnectivityManager) 
            m_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;
}

And to check only wifi is simpler:

private boolean isWifiConnected() {
    int WIFI_STATE = wifi.getWifiState();
    if(WIFI_STATE == WifiManager.WIFI_STATE_ENABLED)
        return true;

    return false;
}


来源:https://stackoverflow.com/questions/7169909/how-to-detect-when-wifi-is-connected-to-internet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!