Android功能点(一)——判断网络是否真正连通

我们知道,当手机上显示网络连接成功时,并不一定可以真的上网。常见的情况是,连上路由后需要进行跳转登录,或者干脆路由连接到网络的端口坏掉。因此在进行网络通讯前,可能需要确认网络是否真正联通。

经典方法


一种常用的方法,也是沿用pc机上查看网络是否联通的方法,就是使用ping命令。要注意ping在windows上和linux上的参数意义是不一样的。使用-c来确定ping的次数。adb shell进入android环境,输入命令,效果如下。这里www.a.shifen.com是百度为了防止攻击而设置的壳地址,可以忽略。
这里写图片描述

那么现在要做的就是在android代码里使用ping命令,代码如下:

Runtime runtime = Runtime.getRuntime();
                  try {
                    Process p = runtime.exec("ping -c 3 www.baidu.com");
                    int ret = p.waitFor();
                    Log.i("Avalible", "Process:"+ret);
                } catch (Exception e) {
                    e.printStackTrace();
                }

然后我们来看下不同网络状态下代码的执行效果:

  1. 连通的移动数据网络下:
    这里写图片描述

  2. 在需要网页认证的wifi下:
    这里写图片描述

  3. 在wifi打开但没有网络连接,数据也不可用的状态下:
    这里写图片描述

  4. 在不可用wifi下:
    这里写图片描述

  5. 在可用wifi下:
    这里写图片描述

基本上只要判断是否是0即可,若是0则网络真正可用。

Android 6.0以上可用方法


在API 21增加了一个类NetworkCapabilities,其中有很多对于网络性能的描述,可以通过ConnectivityManager获得描述当前网络的NetworkCapabilities。而在API23中,增加了一个描述NET_CAPABILITY_VALIDATED。文档中对其描述如下:

Indicates that connectivity on this network was successfully validated. For example, for a network with NET_CAPABILITY_INTERNET, it means that Internet connectivity was successfully detected.

实验表明,当NetworkCapabilities的描述中有VALIDATED这个描述时,此网络是真正可用的。使用如下代码获得当前网络的capabilities:

NetworkCapabilities networkCapabilities = mConnectivityManager.getNetworkCapabilities(mConnectivityManager.getActiveNetwork());
Log.i("Avalible", "NetworkCapalbilities:"+networkCapabilities.toString());

可以看到代码非常简单,将对于NetworkCapabilities的描述打印出来,不同网络状态下结果如下:

  1. 在可联通的wifi下,可看到出现了VALIDATED的标记:
    这里写图片描述
  2. 在需要认证的wifi下,可以看到相应区域没有VALIDATED的标记:
    这里写图片描述
  3. 在不可上网的wifi下,可以看到也没有VALIDATED的标记:
    这里写图片描述
  4. 在移动数据下,可以看到VALIDATED又出现了:
    这里写图片描述

因此可以通过判断这个标记是否存在来判断网络的连通性。通过如下调用来判断标记存在与否:

networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);

可惜只能6.0以上使用,目前还是又很多6.0下的手机在使用的,因此经典方法还是很重要。

http协议


其实查看网络连接是否成功的本质,就是实际去连下,看看能不能连到。所以理论上任何网络通讯协议都可以来处理这件事。但实际上,开发中大多使用经典方法是有道理的。因为ping命令本身就是为了查看网络连通状况而存在。而使用http协议的话,不但数据包会较大、使用较复杂,很多情况也没法处理。下面来简单地用Get去访问url看看会发生什么。代码如下:

HttpURLConnection httpConn = null;
                InputStream inputStream = null;
                int respondcode = -1;
                try{
                    URL url = new URL("http://www.baidu.com");
                    httpConn = (HttpURLConnection)url.openConnection();
                    httpConn.setRequestMethod("GET");
                    respondcode = httpConn.getResponseCode();
                    Log.i("Avalible", "HttpURLConnection1:"+respondcode+" "+httpConn.getHeaderField("Location"));
                    url = new URL(httpConn.getHeaderField("Location"));
                    httpConn = (HttpURLConnection)url.openConnection();
                    httpConn.setUseCaches(false);
                    httpConn.setRequestMethod("GET");
                    respondcode = httpConn.getResponseCode();
                    Log.i("Avalible", "HttpURLConnection2:"+respondcode+" "+httpConn.getHeaderField("Location"));
                }catch(Exception e){
                    e.printStackTrace();

                }

由于可能会发生重定向,因此进行两次http请求,并且将重定向的url打印出来查看。不同网络下结果如下:

  1. 移动数据流量。首先进行了一次跳转,第二次返回200成功:
    这里写图片描述
  2. 可连通wifi下,完全一样:
    这里写图片描述
  3. 需要认证wifi下,返回200,但实际上并没有确认可连通www.baidu.com,只是连接到了需要登录的地址。因此实际上是没法通过返回值来判断究竟能否上网的:
    这里写图片描述
  4. 而在无法上网的情况下,是直接报错的:
    这里写图片描述

因此相对来说,使用http协议,处理的过程更加复杂,返回结果不够明确,相对不适合用来判断网络是否连通。

  • 9
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
RELEASE NOTES: README.txt,v 1.5 2003/02/22 06:21:57 russcoon Exp $_______________________________________________________________________________0.3.0 pre2OVERVIEW: netWindows 0.3 pre2 is fairly close to a release canidate for the 0.3 final release. What‘s included in this release: * the netWindows core * 17 release-quality widgets * per-widget example pages (see /docs/widget_test_pages/) * sample environment pagesCHANGES: * total re-working of all inline constructor parsers * major re-structuring of inline constructor syntax for all widgets that provide inline constructors * Signals and Slots event mechanism now widely used throughout the API * new configuration directives * new ways to apply configuration options * dependency on blank.html removed * CSS-only themeing now available on all widgets * NW_getFileTxt() now supports same-page URL caching * resizeable components can now have minimum and maximum widths and heights * ability to dissable page-wide inline constructor searching (increases load time performance) * ability to provide an explicit array of IDs to be searched for inline constructors as children. Combined with dissabling full page constructor searching, can allow authors that "know what‘s comming" to optimize NW inline constructor performance (espically on large pages) * singleton objects now declared using var __obj__ = new Object(); syntax instead of creating classes for each. Cuts down on possible namespace contention. * __data__ rewritten to support "parser profiles" which allow shallow data requests to be highly optimized using new parsers. * __sig__ now allow arbitrary number of arguments to any method (removing previous hard limit of 13) * __sig__.addBareSig allows non-connected functions and methods to be registered, enhancing anonymity of components. * __util__ now includes methods for setting and getting class and attribute values, abstracting browser-specific problems away * New Widgets! - Split Pane widget: provides user-resizeable (or not) "panes" which can form the basis of many application interface layouts. Provides support for both horizontal and vertical splitting. - Combo Box widget: supports partial (incremental) option matching, first substring matching and any-word substring matching, inline or external file option loading (via NW_getFileTxt(), not __data__), option "groups" to seperate sections of potential options, and optional search indexes for external file inputs. The Combo Box also provides 2 form returns: the text the user inputs into the text box as well as any value that may have matched from the options list, allowing application developers to determine if the user choose from the provided list or wrote in their own value. With external input files (using optional search indexes), the combo-box has been shown to provide good performance on data sets in the 10,000 record range on moderate hardware (~300MHz). - Sort Table: apply this widget constructor to a well-formed HTML table to provide sorting capability to any table! 3 different sort types are available as well as onLoad sorting to provided a sorted table to the user without server-side sorting. (programatic constructor not provided). - Scroll Table: provides a sortable table with headings that always stay in view. Provides runtime addition, removal, and updating of rows. Key-accelerated highlighting. The Scroll Table also supports most of the features of the Sort Table. - Text Expander. A widget that provides a textarea with a twist: it can automatically expand acronyms and shorthand words into full strings of arbitrary length. Handy for text-intensive applications that involve repetitive text entry and/or lots of professiona-specific shorthand and acronyms. The Text Expander also supports "tabbing" between configurable key characters.FEATURES: netWindows represents a new type of DHTML API that helps facilitate the creation and usage of "truly" dynamic interfaces. That is, DHTML interfaces that are created entirely on-the-fly on the client. netWindows is designed to help create and manage these sophisticated web application interfaces. In addition to the widgets provided with this archive, the netWindows core scripts provide the following services to all netWindows pages: * an asynchronous, queued content loading mechanism * automatic tooltip support * on-the-fly theme changing (no page reload required) * keystroke event support * automatic script dependency satisfaction * an advanced, unified event model (signals and slots) * an extensible component framework * automatic environment setup (include a single file and go). The widgets provided with netWindows also provide many features specific to their intended applications, but common features among them include: * true widget anonymity * on-the-fly creation and destruction (developer need not know or care) * inline constructor functions for "codeless" widget instantiation * true seperation of data from presentation logic (even on the client) * almost all widgets are fully themedSUPPORT: netWindows is provided without support or warranty (see license agreement below). This aside, a mailing list is available for those using the toolkit, and the primary netWindows developers watch this list and enjoy and are often happy to answer questions users may have. To subscribe to this list, visit: http://netwindows.org/mailman/listinfo/devel_netwindows.orgDOCUMENTATION: see the netWindows/docs/ directory for documentation and tutorials on both widget usage and the netWindows framework in general.THANKS: For this release, Alex would like to thank Mark Anderson of Discerning Software for his invaluable help, advice, prodding, probing questions, incredible support, and persistant push that has made this release the giant leap above 0.2.4 that I suspected it could be so many long months ago.About netWindows_______________________________________________________________________________netWindows is an Open Source DOM based DHTML API and framework for buildingweb application interfaces. The project strives to provide a standards-compliant development framework and sample applications for developers. Anyone interestedin being part of the project can contact Alex Russell (the project admin) [email protected] NOTICE_______________________________________________________________________________all code in this distribution, all documentation, and any other work provided inthis archive, unless otherwise stated in the file itself, is copyright 2000-2003Alex RussellLICENSE NOTICE_______________________________________________________________________________netWindows is distributed under the Academic Free License, as follows:Copyright (c) 2000-2002 Alex RussellAcademic Free License Version 1.1This Academic Free License applies to any original work of authorship (the"Original Work") whose owner (the "Licensor") has placed the following noticeimmediately following the copyright notice for the Original Work: "Licensedunder the Academic Free License version 1.1."Grant of License. Licensor hereby grants to any person obtaining a copy of theOriginal Work ("You") a world-wide, royalty-free, non-exclusive, perpetual,non-sublicenseable license (1) to use, copy, modify, merge, publish, perform,distribute and/or sell copies of the Original Work and derivative worksthereof, and (2) under patent claims owned or controlled by the Licensor thatare embodied in the Original Work as furnished by the Licensor, to make, use,sell and offer for sale the Original Work and derivative works thereof,subject to the following conditions.Right of Attribution. Redistributions of the Original Work must reproduce allcopyright notices in the Original Work as furnished by the Licensor, both inthe Original Work itself and in any documentation and/or other materialsprovided with the distribution of the Original Work in executable form.Exclusions from License Grant. Neither the names of Licensor, nor the names ofany contributors to the Original Work, nor any of their trademarks or servicemarks, may be used to endorse or promote products derived from this OriginalWork without express prior written permission of the Licensor.WARRANTY AND DISCLAIMERS. LICENSOR WARRANTS THAT THE COPYRIGHT IN AND TO THEORIGINAL WORK IS OWNED BY THE LICENSOR OR THAT THE ORIGINAL WORK ISDISTRIBUTED BY LICENSOR UNDER A VALID CURRENT LICENSE FROM THE COPYRIGHTOWNER. EXCEPT AS EXPRESSLY STATED IN THE IMMEDIATELY PRECEEDING SENTENCE, THEORIGINAL WORK IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUTWARRANTY, EITHER EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, THEWARRANTY OF NON-INFRINGEMENT AND WARRANTIES THAT THE ORIGINAL WORK ISMERCHANTABLE OR FIT FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THEQUALITY OF THE ORIGINAL WORK IS WITH YOU. THIS DISCLAIMER OF WARRANTYCONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO LICENSE TO ORIGINAL WORK ISGRANTED HEREUNDER EXCEPT UNDER THIS DISCLAIMER.LIMITATION OF LIABILITY. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY,WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THELICENSOR BE LIABLE TO ANY PERSON FOR ANY DIRECT, INDIRECT, SPECIAL,INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING AS A RESULT OFTHIS LICENSE OR THE USE OF THE ORIGINAL WORK INCLUDING, WITHOUT LIMITATION,DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION,OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PERSON SHALLHAVE BEEN INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OFLIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY RESULTINGFROM SUCH PARTY‘S NEGLIGENCE TO THE EXTENT APPLICABLE LAW PROHIBITS SUCHLIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OFINCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOTAPPLY TO YOU.License to Source Code. The term "Source Code" means the preferred form of theOriginal Work for making modifications to it and all available documentationdescribing how to access and modify the Original Work. Licensor hereby agreesto provide a machine-readable copy of the Source Code of the Original Workalong with each copy of the Original Work that Licensor distributes. Licensorreserves the right to satisfy this obligation by placing a machine-readablecopy of the Source Code in an information repository reasonably calculated topermit inexpensive and convenient access by You for as long as Licensorcontinues to distribute the Original Work, and by publishing the address ofthat information repository in a notice immediately following the copyrightnotice that applies to the Original Work.Mutual Termination for Patent Action. This License shall terminateautomatically and You may no longer exercise any of the rights granted to Youby this License if You file a lawsuit in any court alleging that any OSICertified open source software that is licensed under any license containingthis "Mutual Termination for Patent Action" clause infringes any patent claimsthat are essential to use that software.This license is Copyright (C) 2002 Lawrence E. Rosen. All rights reserved.Permission is hereby granted to copy and distribute this license withoutmodification. This license may not be modified without the express writtenpermission of its copyright owner.-- END OF LICENSE. The following is intended to describe the essentialdifferences between the Academic Free License (AFL) version 1.0 and otheropen source licenses: The Academic Free License is similar to the BSD, MIT, UoI/NCSA and Apachelicenses in many respects but it is intended to solve a few problems withthose licenses. The AFL is written so as to make it clear what software is being licensed (by the inclusion of a statement following the copyright notice in the software). This way, the license functions better than a template license. The BSD, MIT and UoI/NCSA licenses apply to unidentified software. The AFL contains a complete copyright grant to the software. The BSD and Apache licenses are vague and incomplete in that respect. The AFL contains a complete patent grant to the software. The BSD, MIT, UoI/NCSA and Apache licenses rely on an implied patent license and contain no explicit patent grant. The AFL makes it clear that no trademark rights are granted to the licensor‘s trademarks. The Apache license contains such a provision, but the BSD, MIT and UoI/NCSA licenses do not. The AFL includes the warranty by the licensor that it either owns the copyright or that it is distributing the software under a license. None of the other licenses contain that warranty. All other warranties are disclaimed, as is the case for the other licenses. The AFL is itself copyrighted (with the right granted to copy and distribute without modification). This ensures that the owner of the copyright to the license will control changes. The Apache license contains a copyright notice, but the BSD, MIT and UoI/NCSA licenses do not.CONTACT_______________________________________________________________________________Alex [email protected]://netWindows.orghttp://alex.netWindows.org
判断Android设备是否真正连通网络,可以通过以下步骤: 1. 添加网络状态监听器,监听网络连接状态的变化。 ```java ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkRequest.Builder builder = new NetworkRequest.Builder(); builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET); builder.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR); builder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI); NetworkRequest request = builder.build(); connectivityManager.registerNetworkCallback(request, new ConnectivityManager.NetworkCallback() { @Override public void onAvailable(Network network) { // 网络已连接 } @Override public void onLost(Network network) { // 网络已断开 } }); ``` 2. 判断当前网络是否可用。 ```java ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) { // 网络可用 } else { // 网络不可用 } ``` 3. 使用ping命令测试网络连接。 ```java public static boolean isNetworkConnected() { try { String command = "/system/bin/ping -c 1 8.8.8.8"; return Runtime.getRuntime().exec(command).waitFor() == 0; } catch (IOException | InterruptedException e) { e.printStackTrace(); } return false; } ``` 以上是在Android平台上判断网络是否真正连通的方法,希望能对你有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值