使用:
// 获取网络是否可用
KapNetWorkStatusManager.isNetworkAvailable();
工具类如下:
/**
* Created by jing on 2018/1/29.
* 网络状态
*/
public class KapNetWorkStatusManager {
private static Context getContext(){
return KapApplication.getContext();
}
/**
* 网络是否可用
*
*/
public static boolean isNetworkAvailable() {
Context context = getContext();
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
/**
* wifi是否打开
*/
public static boolean isWifiEnabled() {
Context context = getContext();
ConnectivityManager mgrConn = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
TelephonyManager mgrTel = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
return ((mgrConn.getActiveNetworkInfo() != null && mgrConn
.getActiveNetworkInfo().getState() == NetworkInfo.State.CONNECTED) || mgrTel
.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS);
}
/**
* 判断当前网络是否是wifi网络
* if(activeNetInfo.getType()==ConnectivityManager.TYPE_MOBILE) {
*
* @return boolean
*/
public static boolean isWifi() {
Context context = getContext();
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetInfo != null
&& activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
return true;
}
return false;
}
/**
* 判断当前网络是否3G网络
*
*/
public static boolean is3G() {
Context context = getContext();
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetInfo != null
&& activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
return true;
}
return false;
}
}
网友评论