简体   繁体   English

检查设备是否确实已连接到互联网android

[英]check if device is really connected to the internet android

I am developing an android application and I need to check whether the device is really connected to the internet using the following the method 我正在开发一个android应用程序,我需要使用以下方法检查设备是否真的连接到了互联网

cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            if (cm.getActiveNetworkInfo() != null
                    && cm.getActiveNetworkInfo().isAvailable()
                    && cm.getActiveNetworkInfo().isConnected()) {
                try {
                    URL url = new URL("http://www.google.com");
                    HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
                    urlc.setRequestProperty("Connection", "close");
                    urlc.setConnectTimeout(10 * 1000); // Ten seconds timeout in milliseconds
                    urlc.connect();
                    if (urlc.getResponseCode() == 200) { // success
                        System.out.println("success mobile");
                        return true;
                    } else { // Fail
                        return false;
                    }
                } catch (IOException e) {
                    return false;
                }
            } 
            else 
            {
                return false;
            }

this method works if I disable the mobile data or the wifi. 如果我禁用移动数据或wifi,则此方法有效。 However, in my case the provider simply stopped the internet because I've reached my usage limit or run out of data allowance. 但是,在我的情况下,供应商只是停止了互联网,因为我已达到使用限制或数据余量不足。 So in this case the method returns TRUE even though when I go to the browser and type in google.com it doesn't work and I get the message by the provider that I've reached my limit? 因此,在这种情况下,即使当我进入浏览器并在google.com中键入该方法时,该方法仍会返回TRUE,但该方法无法正常工作,并且提供商收到我已达到极限的消息? So somehow google.com pings as reachable even though I can't open it from the device due to the usage limit? 因此,即使由于使用限制而无法从设备打开google.com ping还是可以访问? I can only access the webpage of my mobile provider where I can buy more allowance so the internet is not switched off but just limited. 我只能访问我的移动服务提供商的网页,在这里我可以购买更多的零用钱,因此互联网不会被关闭,而只能是有限的。 How can I check for that? 我该如何检查?

The best way to do this is to implement time out exception. 最好的方法是实现超时异常。

 HttpGet httpGet = new HttpGet(url); HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. // The default value is zero, that means the timeout is not used. int timeoutConnection = 3000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = 5000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters); HttpResponse response = httpClient.execute(httpGet); 

You could Ping well known public site(s) such as Google's public DNS servers: 8.8.8.8 and 8.8.4.4 , www.cnn.com , www.yahoo.com , etc. 您可以Ping知名的公共站点,例如Google的公共DNS服务器: 8.8.8.8 and 8.8.4.4www.cnn.comwww.yahoo.com等。

This will be a good way to do a 'sanity' check. 这将是进行“健全性”检查的好方法。 (make sure to do this in a background thread in case the device is NOT connected to the internet. Plus I'd mix/match 1 IP and 1 Domain name, that way you can maybe tell the user 'why' your app isn't connecting. (请确保在后台线程中执行此操作,以防设备未连接到互联网。另外,我会混合/匹配1个IP和1个域名,这样您就可以告诉用户“为什么”您的应用是“连接。

But you should probably only do this AFTER your connection attempt to YOUR server fails. 但是,您可能仅应在与服务器的连接尝试失败后执行此操作。 (as that sanity check to tell if YOUR site is down or not) (如进行健全性检查以判断您的网站是否关闭)


THEN if you are able to ping those sites, then try full HTTP connect and verify that the 'page' you are getting is 'correct'. 然后,如果您能够ping通这些站点,则尝试使用完整的HTTP连接并验证所获取的“页面”是否“正确”。 Not just the HTTP response code. 不只是HTTP响应代码。 Because the HTTP MITM (Man in the middle) that your ISP is probably using to redirect your web traffic is going to return 200 because it is a 'valid' page... but not 'the desired' page. 因为您的ISP可能使用重定向你的网站流量的HTTP MITM(中间人) 是否会返回200,因为它是一个“有效”网页...但不是'所需的页面。

You could easily check THIS part by making a few byte webpage on your server that has nothing but a HTML Title of 'HTTP CHECK' and 'GOOD' or something like that in the body. 您可以通过在服务器上制作几个字节的网页来轻松检查此部分,该网页只包含HTML标题“ HTTP CHECK”和“ GOOD”或类似正文的内容。 Then validate that your app gets THAT page (actually check the HTML contents) and not 'something else' (such as a Paywall). 然后,验证您的应用是否可以访问该页面(实际上是检查HTML内容),而不是“其他”内容(例如Paywall)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM