在开发的时候,往往会遇到在获取数据的时候,突然就把网络关闭的情况,如果后天没有写完善的话,就会直接出去crash。所以在请求的时候很有必要做好用户友好化。
今天和大家分享下android网络的判断:
1.判断是否有网络:
<span > </span>public boolean validateInternet() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (manager == null) {
return false;
} else {
NetworkInfo[] info = manager.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
注:别忘了添加权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
2.判断是否为WiFi网络
public static boolean isWifiActive(Context icontext){
Context context = icontext.getApplicationContext();
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] info;
if (connectivity != null) {
info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getTypeName().equals("WIFI") && info[i].isConnected()) {
return true;
}
}
}
}
return false;
}
3.判断是否为3g网络
public static boolean is3G(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
return true;
}
return false;
}