How to detect when WIFI is connected to internet?

别等时光非礼了梦想. 提交于 2019-12-04 16:46:09

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

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();
        }

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

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