在Android开发中,我们有时候需要根据当前网络的类型去做一些操作,下面看看如何判断当前网络的状况:
public class NetWorkUtil {
private static ConnectivityManager manager;
/**
* 判断网络是否连接
* @param context
* @return
*/
public static boolean isNetWorkAvailable(Context context){
boolean flag = false;
manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if(manager.getActiveNetworkInfo()!=null){
flag = manager.getActiveNetworkInfo().isAvailable();
}
return flag;
}
/**
* 判断当前网络类型
* @param context
* @return 1 代表gps,2代表wifi
*/
public static int getNetworkType(Context context){
int type = 0 ;
State gprs = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
State wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
if(gprs == State.CONNECTED || gprs == State.CONNECTING){
type = 1;
}
if(wifi == State.CONNECTED || wifi == State.CONNECTING){
type = 2;
}
return type;
}
/**
* 判断移动网络是否连接
* @param context
* @return
* @throws Exception
*/
public static boolean isMobileDataEnable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
boolean isMobileDataEnable = false;
isMobileDataEnable = connectivityManager.getNetworkInfo(
ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();
return isMobileDataEnable;
}
/**
* 判断wifi是否连接
* @param context
* @return
* @throws Exception
*/
public static boolean isWifiDataEnable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
boolean isWifiDataEnable = false;
isWifiDataEnable = connectivityManager.getNetworkInfo(
ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
return isWifiDataEnable;
}
}