您的位置:首页 > 理论基础 > 计算机网络

判断网络是否,gps,wifi是否开启

2016-05-17 15:12 357 查看
import android.content.Context;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import android.util.Log;

public class NetUtil {
/**
* 判断Network是否开启(包括移动网络和wifi),并且链接成功
*/
public static boolean isNetworkSuccess(Context mContext) {
return (isNetworkEnabled(mContext) && isNetworkConnected(mContext));
}

/**
* 判断Network是否开启(包括移动网络和wifi)
*
* @return
*/
public static boolean isNetworkEnabled(Context mContext) {
return (isNetEnabled(mContext) || isWIFIEnabled(mContext));
}

/**
* 判断Network是否连接成功(包括移动网络和wifi)
*/
public static boolean isNetworkConnected(Context mContext) {
return (isWifiContected(mContext) || isNetContected(mContext));
}

/**
* 判断移动网络是否开启
*
* @return
*/
public static boolean isNetEnabled(Context context) {
boolean enable = false;
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager != null) {
if (telephonyManager.getNetworkType()!=TelephonyManager.NETWORK_TYPE_UNKNOWN) {
enable = true;
}
}

return enable;
}

/**
* 判断wifi是否开启
*/
public static boolean isWIFIEnabled(Context context) {
boolean enable = false;
WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
if (wifiManager.isWifiEnabled()) {
enable = true;
}
return enable;
}

/**
* 判断移动网络是否连接成功!
*
* @param context
* @return
*/
public static boolean isNetContected(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mobileNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (mobileNetworkInfo.isConnected()) {
return true;
}
return false;

}

/**
* 判断wifi是否连接成功
*
* @param context
* @return
*/
public static boolean isWifiContected(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifiNetworkInfo.isConnected()) {
return true;
}
return false;

}

/**
* 判断GPS是否开启,GPS开启一个就认为是开启的
* @param context
* @return true 表示开启
*/
public static final boolean mGps(final Context context) {
LocationManager locationManager= (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
// 通过GPS卫星定位
boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(gps){
return  true;
}
return false;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: