在开发中某些项目我们需要判断当前网络转台详细情况,来做一些限制,对于android手机,我们可以通过sdk提供的方法判断网络情况/**
* 获取当前的网络状态 :没有网络-0:WIFI网络1:4G网络-4:3G网络-3:2G网络-2
* 自定义
*
* @param context
* @return
*/
public static int getAPNType(Context context) {
//结果返回值
int netType = 0;
//获取手机所有连接管理对象
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
//获取NetworkInfo对象
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
//NetworkInfo对象为空 则代表没有网络
if (networkInfo == null) {
return netType;
}
//否则 NetworkInfo对象不为空 则获取该networkInfo的类型
int nType = networkInfo.getType();
if (nType == ConnectivityManager.TYPE_WIFI) {
//WIFI
netType = 1;
} else if (nType == ConnectivityManager.TYPE_MOBILE) {
int nSubType = networkInfo.getSubtype();
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
//3G 联通的3G为UMTS或HSDPA 电信的3G为EVDO
if (nSubType == TelephonyManager.NETWORK_TYPE_LTE
&& !telephonyManager.isNetworkRoaming()) {
netType = 4;
} else if (nSubType == TelephonyManager.NETWORK_TYPE_UMTS
|| nSubType == TelephonyManager.NETWORK_TYPE_HSDPA
|| nSubType == TelephonyManager.NETWORK_TYPE_EVDO_0
&& !telephonyManager.isNetworkRoaming()) {
netType = 3;
//2G 移动和联通的2G为GPRS或EGDE,电信的2G为CDMA
} else if (nSubType == TelephonyManager.NETWORK_TYPE_GPRS
|| nSubType == TelephonyManager.NETWORK_TYPE_EDGE
|| nSubType == TelephonyManager.NETWORK_TYPE_CDMA
&& !telephonyManager.isNetworkRoaming()) {
netType = 2;
} else {
netType = 2;
}
}
return netType;
} 注意的是对于Tv项目,android系统的Tv(比如小米电视),有的是支持有线连接的(非wifi,2g 3g 4g)的 , 此时上述方法会判断为0,无网络连接状态,所以对于Tv项目,需要对网络适配进行兼容
解决办法就是ping一个外网。/*
* @category 判断是否有外网连接(普通方法不能判断外网的网络是否连接,比如连接上局域网)
* @return
*/
public static final boolean ping() {
String result = null;
try {
String ip = "www.baidu.com";// ping 的地址,可以换成任何一种可靠的外网
Process p = Runtime.getRuntime().exec("ping -c 3 -w 100 " + ip);// ping网址3次
// 读取ping的内容,可以不加
InputStream input = p.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(input));
StringBuffer stringBuffer = new StringBuffer();
String content = "";
while ((content = in.readLine()) != null) {
stringBuffer.append(content);
}
Log.d("------ping-----", "result content : " + stringBuffer.toString());
// ping的状态
int status = p.waitFor();
if (status == 0) {
result = "success";
return true;
} else {
result = "failed";
}
} catch (IOException e) {
result = "IOException";
} catch (InterruptedException e) {
result = "InterruptedException";
} finally {
Log.d("----result---", "result = " + result);
}
return false;
} 可以对网络状态进行: 有线/wifi/2g/3g/4g的区分//获取网络连接状态
int apnType = NetworkUtils.getAPNType(getActivty);
if (apnType == 0) {
if (ping()) {
//极端情况下没有外网连接的wifi,或者有线连接
} else {
//无网络
}
} else if (apnType == 1) {
//wifi
} else if (apnType == 2) {
//2g
} else if (apnType == 3) {
//3g
} else if (apnType == 4) {
//4g
}
|