Display an alert when internet connection not available in android application

后端 未结 13 778
有刺的猬
有刺的猬 2020-12-08 11:48

In my application data comes from internet and I am trying to create a function that checks if a internet connection is available or not and if it isn\'t, it gives an alert

13条回答
  •  旧时难觅i
    2020-12-08 12:25

    The above method just informs you whether your mobile has the possibility to connect to the internet, however, it does not tell exactly if connectivity exists.. for example, you might be able to connect to a wifi, but be in a coffee shop where you should enter credentials into a hot spot website... or , your home wifi might be working, and you are connected to it, but cannot access internet. Use the below code to check for internet connetivity. it is preferable to use this inside an asynctask.

    public boolean hasActiveInternetConnection()
    {
            try
            {
                HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
                urlc.setRequestProperty("User-Agent", "Test");
                urlc.setRequestProperty("Connection", "close");
                urlc.setConnectTimeout(4000);
                urlc.setReadTimeout(4000);
                urlc.connect();
                networkcode2 = urlc.getResponseCode();
                return (urlc.getResponseCode() == 200);
            } catch (IOException e)
            {
                Log.i("warning", "Error checking internet connection", e);
                return false;
            }
    
    } 
    

提交回复
热议问题