Android regular check for internet connection

前端 未结 3 1287
[愿得一人]
[愿得一人] 2021-01-14 23:15

I\'m running an android app that displays a webview on specific URL, I want to check if the application server I\'m accessing is alive and that I can view HTML, if failed I

3条回答
  •  迷失自我
    2021-01-14 23:31

    Create Timer (here you have information) and when timer tick, ping any host :

     URL url = new URL("http://microsoft.com");
    
        HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
        urlc.setRequestProperty("User-Agent", "Android Application:"+Z.APP_VERSION);
        urlc.setRequestProperty("Connection", "close");
        urlc.setConnectTimeout(1000 * 30); // mTimeout is in seconds
                urlc.connect();
        if (urlc.getResponseCode() == 200) {
            Main.Log("getResponseCode == 200");
                return new Boolean(true);
        }
        } catch (MalformedURLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
    } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
        } 
    

    If return true : connection is active. Else isn't active.

提交回复
热议问题