App判断用户是否联网是很普遍的需求,这篇文章主要介绍了Android中判断网络连接状态的方法,感兴趣的朋友可以参考一下
App判断用户是否联网是很普遍的需求,这篇文章主要介绍了Android中判断网络连接状态的方法,感兴趣的朋友可以参考一下
App判断用户是否联网是很普遍的需求,这篇文章主要介绍了Android中判断网络连接状态的方法,感兴趣的朋友可以参考一下
app判断用户是否联网是很普遍的需求,实现思路大概有下面几种
1、判断网络是否已经连接
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
// check all network connect, wifi or mobilepublic static boolean isnetworkavailable(final context context) { boolean haswifocon = false; boolean hasmobilecon = false; connectivitymanager cm = (connectivitymanager) context.getsystemservice(context.connectivity_service); networkinfo[] netinfos = cm.getallnetworkinfo(); for (networkinfo net : netinfos) { string type = net.gettypename(); if (type.equalsignorecase("wifi")) { levellogutils.getinstance().i(tag, "get wifi connection"); if (net.isconnected()) { haswifocon = true; } } if (type.equalsignorecase("mobile")) { levellogutils.getinstance().i(tag, "get mobile connection"); if (net.isconnected()) { hasmobilecon = true; } } } return haswifocon || hasmobilecon; } |
2、利用 ping 判断 internet 能够 请求成功
note:有时候连上了网络, 但却上不去外网
|
1
2
3
4
5
6
7
8
9
10
11
12
|
// network available cannot ensure internet is availablepublic static boolean isnetworkavailable(final context context) { runtime runtime = runtime.getruntime(); try { process pingprocess = runtime.exec("/system/bin/ping -c 1 www.baidu.com"); int exitcode = pingprocess.waitfor(); return (exitcode == 0); } catch (exception e) { e.printstacktrace(); } return false;} |
考虑到网络, 我们 ping 了www.baidu.com
国外的话可以 ping 8.8.8.8
3、其他方案 模拟 get 请求
也可以访问网址, 看 get 请求能不能成功
|
1
2
3
4
5
6
7
|
url url = new url("http://www.google.com");httpurlconnection urlc = (httpurlconnection) url.openconnection();urlc.setconnecttimeout(3000);urlc.connect();if (urlc.getresponsecode() == 200) { return new boolean(true);} |
以上就是本文的全部内容,希望对大家学习android软件编程有所帮助。
发表评论