Android to determine whether you can surf the internet, commonly used is the following method:
?
1234567891011121314 |
/**
* 检测网络是否连接
*
* @return
*/
private boolean isNetworkAvailable() {
// 得到网络连接信息
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// 去进行判断网络是否连接
if (manager.getActiveNetworkInfo() !=
null
) {
return manager.getActiveNetworkInfo().isAvailable();
}
return false
;
}
|
However, sometimes we connect to a network that does not have an extranet connection or need to enter an account and password to link to an extranet, which can occur although the network is available, but the extranet is not accessible. In response to this situation, the general solution is to ping an external network, if you can ping the instructions can really surf the internet, the code is as follows
?
1234567891011121314151617181920212223242526272829303132333435 |
*
@author
sichard
*
@category 判断是否有外网连接(普通方法不能判断外网的网络是否连接,比如连接上局域网)
*
@return
*/
public
static
final
boolean
ping() {
String result =
null
;
try
{
String ip =
"www.baidu.com"
;
// ping 的地址,可以换成任何一种可靠的外网
Process p = Runtime.getRuntime().exec(
"ping -c 3 -w 100 "
+ ip);
// ping网址3次
// 读取ping的内容,可以不加
InputStream input = p.getInputStream();
BufferedReader in =
new
BufferedReader(
new
InputStreamReader(input));
StringBuffer stringBuffer =
new
StringBuffer();
String content =
""
;
while
((content = in.readLine()) !=
null
) {
stringBuffer.append(content);
}
Log.d(
"------ping-----"
,
"result content : "
+ stringBuffer.toString());
// ping的状态
int
status = p.waitFor();
if
(status ==
0
) {
result =
"success"
;
return
true
;
}
else
{
result =
"failed"
;
}
}
catch
(IOException e) {
result =
"IOException"
;
}
catch
(InterruptedException e) {
result =
"InterruptedException"
;
}
finally
{
Log.d(
"----result---"
,
"result = "
+ result);
}
return
false
;
|
Push family, free tickets, scenic spots: www.tuituizu.com
A companion tour, a free dating site: www.jieberu.com
Android to determine if you can really surf the internet