通常对于android手机,咱们能够经过sdk提供的方法判断网络状况android
/** * 获取当前的网络状态 :没有网络-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一个外网。app
/* * @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的区分spa