Android中判断网络连接状态的方法
App判断用户是否联网是很普遍的需求,实现思路大概有下面几种
- 利用Android自带的ConnectivityManager类
- 有时候连上了wifi,但这个wifi是上不了网的,我们可以通过pingwww.baidu.com来判断是否可以上网
- 也可以利用get请求访问www.baidu.com,如果get请求成功,说明可以上网
1、判断网络是否已经连接
//checkallnetworkconnect,WIFIormobile publicstaticbooleanisNetworkAvailable(finalContextcontext){ booleanhasWifoCon=false; booleanhasMobileCon=false; ConnectivityManagercm=(ConnectivityManager)context.getSystemService(context.CONNECTIVITY_SERVICE); NetworkInfo[]netInfos=cm.getAllNetworkInfo(); for(NetworkInfonet:netInfos){ Stringtype=net.getTypeName(); if(type.equalsIgnoreCase("WIFI")){ LevelLogUtils.getInstance().i(tag,"getWificonnection"); if(net.isConnected()){ hasWifoCon=true; } } if(type.equalsIgnoreCase("MOBILE")){ LevelLogUtils.getInstance().i(tag,"getMobileconnection"); if(net.isConnected()){ hasMobileCon=true; } } } returnhasWifoCon||hasMobileCon; }
2、利用ping判断Internet能够请求成功
Note:有时候连上了网络,但却上不去外网
//networkavailablecannotensureInternetisavailable publicstaticbooleanisNetWorkAvailable(finalContextcontext){ Runtimeruntime=Runtime.getRuntime(); try{ ProcesspingProcess=runtime.exec("/system/bin/ping-c1www.baidu.com"); intexitCode=pingProcess.waitFor(); return(exitCode==0); }catch(Exceptione){ e.printStackTrace(); } returnfalse; }
考虑到网络,我们ping了www.baidu.com
国外的话可以ping8.8.8.8
3、其他方案模拟get请求
也可以访问网址,看get请求能不能成功
URLurl=newURL("http://www.google.com"); HttpURLConnectionurlc=(HttpURLConnection)url.openConnection(); urlc.setConnectTimeout(3000); urlc.connect(); if(urlc.getResponseCode()==200){ returnnewBoolean(true); }
以上就是本文的全部内容,希望对大家学习Android软件编程有所帮助。