how to check that internet on local wifi is availa

2019-02-20 08:04发布

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条回答
Root(大扎)
2楼-- · 2019-02-20 08:55

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;

    }
}
查看更多
登录 后发表回答