本人是要判断网络连接能否可用,例如:手机连上了一个WiFi,但是这个WiFi无法访问网络,这种情况怎么样判断?
解决方案
10
参考下贴:
http://stackoverflow.com/questions/16580380/how-to-check-wifi-is-connected-but-no-internet-access-in-android
http://stackoverflow.com/questions/16580380/how-to-check-wifi-is-connected-but-no-internet-access-in-android
public void checkOnlineState() { ConnectivityManager CManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo NInfo = CManager.getActiveNetworkInfo(); if (NInfo != null && NInfo.isConnectedOrConnecting()) { if (InetAddress.getByName("www.xy.com").isReachable(timeout)) { // host reachable } else { // host not reachable } } return; }
加上权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
5
连接上Wi-Fi以后,连接一个公共的网站试试
10
www.xy.com这个网址需要替换为可以访问的网址
55
重贴一个可以用的实例吧:
public void checkOnlineState() { ConnectivityManager CManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo NInfo = CManager.getActiveNetworkInfo(); try{ if (NInfo != null && NInfo.isConnectedOrConnecting()) { if (InetAddress.getByName("www.163.com").isReachable(1000)) { Log.d("demo","reach"); // host reachable } else { // host not reachable Log.d("demo","not reach"); } }else{ Log.d("demo","not connect"); } }catch (Exception e){ e.printStackTrace(); } return; }