巴扎黑2017-04-17 14:42:07
public static int getNetWorkStatus(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
NetworkInfo networkInfo = connectivityManager
.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
return NETWORK_WIFI_CONNECTION;
}
return NETWORK_MOBILE_CONNECTION;
}
}
return NETWORK_DISCONNECTION;
}
PHP中文网2017-04-17 14:42:07
If you just want to check whether the network is connected, use it directly isNetworkConnected()
If you want to check the network connectivity (whether the network can be accessed), then use isNetworkConnected()
in combination with isNetworkOnline()
private boolean isNetworkConnected() {
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
return (networkInfo != null && networkInfo.isConnected());
}
public boolean isNetworkOnline() {
Runtime runtime = Runtime.getRuntime();
try {
Process ipProcess = runtime.exec("ping -c 1 114.114.114.114");
int exitValue = ipProcess.waitFor();
return (exitValue == 0);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return false;
}
Note: 114.114.114.114 can be changed to a website you trust (for example: www.baidu.com)
ringa_lee2017-04-17 14:42:07
Personal experience, don’t spray if you don’t like it. . .
I never care whether the user is connected to 3G, 4G or WIFI, and I don’t care whether the WIFI is connected to the Internet, because it doesn’t matter.
The key point is whether the user’s App can connect to the designated server.
So...
Just test the connection to the server directly. If there is no Internet connection, an exception will be thrown quickly.
Try catch and you will know.
Or write a dedicated API for testing connections.
黄舟2017-04-17 14:42:07
Write a method directly and visit http://www.baidu.com. If data is returned, it means there is a network. If no data is returned, or an exception means there is no network. so