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

前端 未结 1 1662
一生所求
一生所求 2021-01-16 07:31

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条回答
  • 2021-01-16 08:02

    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;
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题