App to determine whether users are connected to the network is a very common demand, the realization of the idea is probably the following several
- Take advantage of Android's own Connectivitymanager class
- Sometimes wifi, but this wifi is not on the net, we can ping www.baidu.com to determine whether the Internet
- You can also access www.baidu.com using a GET request, which means that if a GET request succeeds, you can surf the internet
1, to determine whether the network has been connected
Check all network Connect, WIFI or mobile public
static Boolean isnetworkavailable (final context) {
Boo Lean 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, using ping to determine the Internet can request success
Note: sometimes connected to the network, but not to the extranet
Network available cannot ensure Internet is available public
static Boolean isnetworkavailable (final context Contex T) {
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;
}
Considering the network, we ping the www.baidu.com
Foreign words can ping 8.8.8.8
3. Other schemes simulate GET requests
You can also visit the Web site to see if a GET request succeeds
URL url = new URL ("http://www.google.com");
HttpURLConnection URLC = (httpurlconnection) url.openconnection ();
Urlc.setconnecttimeout (3000);
Urlc.connect ();
if (urlc.getresponsecode () = =) {return
new Boolean (TRUE);
}
This is the entire content of this article, I hope to learn more about Android software programming help.