package com.txsc.utils;
import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
/**
* Network tools
*
* @author linshao
*
*/
public class NetUtils {
/**
* 获取 NetWorkInfo
*
* @param context
*
* @return
*/
private static NetworkInfo getNetWorkInfo(Context context) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
return mNetworkInfo;
}
/**
* To determine whether the network is available
*
* @param context
* @return
*/
public boolean isNetworkConnected(Context context) {
if (context != null) {
NetworkInfo mNetworkInfo = getNetWorkInfo(context);
if (mNetworkInfo != null) {
return mNetworkInfo.isAvailable();
}
}
return false;
}
/**
* 获取当前网络类型
*
* @return 0:没有网络 1:WIFI网络 2:WAP网络 3:NET网络
*/
@SuppressLint("DefaultLocale")
public static int getNetworkType(Context mContext) {
int netType = 0;
NetworkInfo networkInfo = getNetWorkInfo(mContext);
if (networkInfo == null) {
return netType;
}
int nType = networkInfo.getType();
if (nType == ConnectivityManager.TYPE_MOBILE) {
String extraInfo = networkInfo.getExtraInfo();
if (!isEmpty(extraInfo)) {
if (extraInfo.toLowerCase().equals("cmnet")) {
netType = 3;
} else {
netType = 2;
}
}
} else if (nType == ConnectivityManager.TYPE_WIFI) {
netType = 1;
}
return netType;
}
/**
* 判断给定字符串是否空白串。 空白串是指由空格、制表符、回车符、换行符组成的字符串 若输入字符串为null或空字符串,返回true
*
* @param input
* @return boolean
*/
public static boolean isEmpty(String input) {
if (input == null || "".equals(input))
return true;
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
return false;
}
}
return true;
}
}