how to check that internet on local wifi is available or not?

笑着哭i 提交于 2019-12-01 11:08:37

问题


I need to check oin my app that internet on local wifi is available or not , i tried

requestRouteToHost but it always returning false , so please help


回答1:


Here is the best way to test if the device has INTERNET connection period.

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;

}

Here's a way to check if it has wifi connection or data connection.

  private boolean checkInternetConnection()
  {

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

    // ARE WE CONNECTED TO THE NET

    if (conMgr.getActiveNetworkInfo() != null

            && conMgr.getActiveNetworkInfo().isAvailable()

            && conMgr.getActiveNetworkInfo().isConnected()) 
    {

    return true;

    }
    else 
    {
    return false;

    }
}


来源:https://stackoverflow.com/questions/8535092/how-to-check-that-internet-on-local-wifi-is-available-or-not

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