网络连接

与网络相关的,就经常要做网络状态判断及信息获取。

用到的类ConnectivityManager 和NetworkInfo
                //获取网络连接管理者
                ConnectivityManager connectionManager = (ConnectivityManager)      
                           context.getSystemService(Context.CONNECTIVITY_SERVICE);   
                //获取网络的状态信息,有下面三种方式
                NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();
                getDetailedState():获取详细状态。
                getExtraInfo():获取附加信息。
                getReason():获取连接失败的原因。
                getType():获取网络类型(一般为移动或Wi-Fi)。
                getTypeName():获取网络类型名称(一般取值“WIFI”或“MOBILE”)。
                isAvailable():判断该网络是否可用。
                isConnected():判断是否已经连接。
                isConnectedOrConnecting():判断是否已经连接或正在连接。
                isFailover():判断是否连接失败。
                isRoaming():判断是否漫游
               
               
                当用wifi上的时候
                getType 是WIFI
                getExtraInfo是空的
               
                当用手机上的时候
                getType 是MOBILE
                用移动CMNET方式
                getExtraInfo 的值是cmnet
                用移动CMWAP方式
                getExtraInfo 的值是cmwap   但是不在代理的情况下访问普通的网站访问不了
                用联通3gwap方式
                getExtraInfo 的值是3gwap
                用联通3gnet方式
                getExtraInfo 的值是3gnet
                用联通uniwap方式
                getExtraInfo 的值是uniwap
                用联通uninet方式
                getExtraInfo 的值是uninet



尝试以下方法获取networktype

  1. TelephonyManager telephonyManager =  
  2.                     (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
  3.                 int networkType = telephonyManager.getNetworkType();
  4.                
  5.                 Log.e("network Type", networkType + "");
  6.                 Log.e("network CountryIso", telephonyManager.getNetworkCountryIso());
  7.                 Log.e("network Operator", telephonyManager.getNetworkOperator());
  8.                 Log.e("network OperatorName", telephonyManager.getNetworkOperatorName());
复制代码


其中:
  1. /** Network type is unknown */
  2.             //public static final int NETWORK_TYPE_UNKNOWN = 0;
  3.             /** Current network is GPRS */
  4.                 //public static final int NETWORK_TYPE_GPRS = 1;
  5.             /** Current network is EDGE */
  6.                 //public static final int NETWORK_TYPE_EDGE = 2;
  7.             /** Current network is UMTS */
  8.                 //public static final int NETWORK_TYPE_UMTS = 3;
  9.             /** Current network is CDMA: Either IS95A or IS95B*/
  10.                 //public static final int NETWORK_TYPE_CDMA = 4;
  11.             /** Current network is EVDO revision 0*/
  12.                 //public static final int NETWORK_TYPE_EVDO_0 = 5;
  13.             /** Current network is EVDO revision A*/
  14.                 //public static final int NETWORK_TYPE_EVDO_A = 6;
  15.             /** Current network is 1xRTT*/
  16.                 //public static final int NETWORK_TYPE_1xRTT = 7;
  17.             /** Current network is HSDPA */
  18.                 //public static final int NETWORK_TYPE_HSDPA = 8;
  19.             /** Current network is HSUPA */
  20.                 //public static final int NETWORK_TYPE_HSUPA = 9;
  21.             /** Current network is HSPA */
  22.                 //public static final int NETWORK_TYPE_HSPA = 10;
  23.             /** Current network is iDen */
  24.                 //public static final int NETWORK_TYPE_IDEN = 11;
复制代码




下面总结一些常用方法:


  1. package com.ltc.demo.networkinfo;

  2. import java.net.InetAddress;
  3. import java.net.NetworkInterface;
  4. import java.net.SocketException;
  5. import java.util.Enumeration;

  6. import android.content.Context;
  7. import android.net.ConnectivityManager;
  8. import android.net.NetworkInfo;
  9. import android.net.wifi.WifiInfo;
  10. import android.net.wifi.WifiManager;
  11. import android.telephony.TelephonyManager;
  12. import android.util.Log;

  13. /**
  14. * 网络信息
  15. *
  16. * @author litingchang
  17. *
  18. */
  19. public class NetworkUtil {
  20.        
  21.         private static final String TAG = "NetworkUtil";

  22.         /**
  23.          * 判断网络是否可用 <br>
  24.          * code from: http://www.androidsnippets.com/have-internet
  25.          *
  26.          * @param context
  27.          * @return
  28.          */
  29.         public static boolean haveInternet(Context context) {
  30.                 NetworkInfo info = (NetworkInfo) ((ConnectivityManager) context
  31.                                 .getSystemService(Context.CONNECTIVITY_SERVICE))
  32.                                 .getActiveNetworkInfo();

  33.                 if (info == null || !info.isConnected()) {
  34.                         return false;
  35.                 }
  36.                 if (info.isRoaming()) {
  37.                         // here is the roaming option you can change it if you want to
  38.                         // disable internet while roaming, just return false
  39.                         // 是否在漫游,可根据程序需求更改返回值
  40.                         return false;
  41.                 }
  42.                 return true;
  43.         }
  44.        
  45.         /**
  46.          * 判断网络是否可用
  47.          * @param context
  48.          * @return
  49.          */
  50.         public static boolean isnetWorkAvilable(Context context) {
  51.                 ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
  52.                 if(connectivityManager == null) {
  53.                         Log.e(TAG, "couldn't get connectivity manager");
  54.                 } else {
  55.                         NetworkInfo [] networkInfos = connectivityManager.getAllNetworkInfo();
  56.                         if(networkInfos != null){
  57.                                 for (int i = 0, count = networkInfos.length; i < count; i++) {
  58.                                         if(networkInfos[i].getState() == NetworkInfo.State.CONNECTED){
  59.                                                 return true;
  60.                                         }
  61.                                 }
  62.                         }
  63.                 }
  64.                 return false;
  65.         }

  66.         /**
  67.          * IP地址<br>
  68.          * code from:
  69.          * http://www.droidnova.com/get-the-ip-address-of-your-device,304.html <br>
  70.          *
  71.          * @return 如果返回null,证明没有网络链接。 如果返回String,就是设备当前使用的IP地址,不管是WiFi还是3G
  72.          */
  73.         public static String getLocalIpAddress() {
  74.                 try {
  75.                         for (Enumeration<NetworkInterface> en = NetworkInterface
  76.                                         .getNetworkInterfaces(); en.hasMoreElements();) {
  77.                                 NetworkInterface intf = en.nextElement();
  78.                                 for (Enumeration<InetAddress> enumIpAddr = intf
  79.                                                 .getInetAddresses(); enumIpAddr.hasMoreElements();) {
  80.                                         InetAddress inetAddress = enumIpAddr.nextElement();
  81.                                         if (!inetAddress.isLoopbackAddress()) {
  82.                                                 return inetAddress.getHostAddress().toString();
  83.                                         }
  84.                                 }
  85.                         }
  86.                 } catch (SocketException ex) {
  87.                         Log.e("getLocalIpAddress", ex.toString());
  88.                 }
  89.                 return null;
  90.         }

  91.         /**
  92.          * 获取MAC地址 <br>
  93.          * code from: http://orgcent.com/android-wifi-mac-ip-address/
  94.          *
  95.          * @param context
  96.          * @return
  97.          */
  98.         public static String getLocalMacAddress(Context context) {
  99.                 WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
  100.                 WifiInfo info = wifi.getConnectionInfo();
  101.                 return info.getMacAddress();
  102.         }
  103.        
  104.         /**
  105.          * WIFI 是否可用
  106.          * @param context
  107.          * @return
  108.          */
  109.         public static boolean isWiFiActive(Context context) {
  110.                 ConnectivityManager connectivity = (ConnectivityManager) context  
  111.                 .getSystemService(Context.CONNECTIVITY_SERVICE);  
  112.         if (connectivity != null) {  
  113.             NetworkInfo[] info = connectivity.getAllNetworkInfo();  
  114.             if (info != null) {  
  115.                 for (int i = 0; i < info.length; i++) {  
  116.                     if (info[i].getTypeName().equals("WIFI") && info[i].isConnected()) {  
  117.                         return true;  
  118.                     }  
  119.                 }  
  120.             }  
  121.         }  
  122.         return false;
  123.         }
  124.        
  125.         /**
  126.          * 存在多个连接点
  127.          * @param context
  128.          * @return
  129.          */
  130.         public static boolean hasMoreThanOneConnection(Context context){
  131.                 ConnectivityManager manager = (ConnectivityManager)context
  132.                         .getSystemService(Context.CONNECTIVITY_SERVICE);
  133.                 if(manager==null){
  134.                         return false;
  135.                 }else{
  136.                         NetworkInfo [] info = manager.getAllNetworkInfo();
  137.                         int counter = 0;
  138.                         for(int i = 0 ;i<info.length;i++){
  139.                                 if(info[i].isConnected()){
  140.                                         counter++;
  141.                                 }
  142.                         }
  143.                         if(counter>1){
  144.                                 return true;
  145.                         }
  146.                 }
  147.                
  148.                 return false;
  149.         }
  150.        
  151.         /*
  152.      * HACKISH: These constants aren't yet available in my API level (7), but I need to handle these cases if they come up, on newer versions
  153.      */
  154.     public static final int NETWORK_TYPE_EHRPD=14; // Level 11
  155.     public static final int NETWORK_TYPE_EVDO_B=12; // Level 9
  156.     public static final int NETWORK_TYPE_HSPAP=15; // Level 13
  157.     public static final int NETWORK_TYPE_IDEN=11; // Level 8
  158.     public static final int NETWORK_TYPE_LTE=13; // Level 11

  159.     /**
  160.      * Check if there is any connectivity
  161.      * @param context
  162.      * @return
  163.      */
  164.     public static boolean isConnected(Context context){
  165.         ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  166.         NetworkInfo info = cm.getActiveNetworkInfo();
  167.         return (info != null && info.isConnected());
  168.     }
  169.     /**
  170.      * Check if there is fast connectivity
  171.      * @param context
  172.      * @return
  173.      */
  174.     public static boolean isConnectedFast(Context context){
  175.         ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  176.         NetworkInfo info = cm.getActiveNetworkInfo();
  177.         return (info != null && info.isConnected() && isConnectionFast(info.getType(),info.getSubtype()));
  178.     }

  179.     /**
  180.      * Check if the connection is fast
  181.      * @param type
  182.      * @param subType
  183.      * @return
  184.      */
  185.     public static boolean isConnectionFast(int type, int subType){
  186.         if(type==ConnectivityManager.TYPE_WIFI){
  187.             System.out.println("CONNECTED VIA WIFI");
  188.             return true;
  189.         }else if(type==ConnectivityManager.TYPE_MOBILE){
  190.             switch(subType){
  191.             case TelephonyManager.NETWORK_TYPE_1xRTT:
  192.                 return false; // ~ 50-100 kbps
  193.             case TelephonyManager.NETWORK_TYPE_CDMA:
  194.                 return false; // ~ 14-64 kbps
  195.             case TelephonyManager.NETWORK_TYPE_EDGE:
  196.                 return false; // ~ 50-100 kbps
  197.             case TelephonyManager.NETWORK_TYPE_EVDO_0:
  198.                 return true; // ~ 400-1000 kbps
  199.             case TelephonyManager.NETWORK_TYPE_EVDO_A:
  200.                 return true; // ~ 600-1400 kbps
  201.             case TelephonyManager.NETWORK_TYPE_GPRS:
  202.                 return false; // ~ 100 kbps
  203.             case TelephonyManager.NETWORK_TYPE_HSDPA:
  204.                 return true; // ~ 2-14 Mbps
  205.             case TelephonyManager.NETWORK_TYPE_HSPA:
  206.                 return true; // ~ 700-1700 kbps
  207.             case TelephonyManager.NETWORK_TYPE_HSUPA:
  208.                 return true; // ~ 1-23 Mbps
  209.             case TelephonyManager.NETWORK_TYPE_UMTS:
  210.                 return true; // ~ 400-7000 kbps
  211.             // NOT AVAILABLE YET IN API LEVEL 7
  212.             case NETWORK_TYPE_EHRPD:
  213.                 return true; // ~ 1-2 Mbps
  214.             case NETWORK_TYPE_EVDO_B:
  215.                 return true; // ~ 5 Mbps
  216.             case NETWORK_TYPE_HSPAP:
  217.                 return true; // ~ 10-20 Mbps
  218.             case NETWORK_TYPE_IDEN:
  219.                 return false; // ~25 kbps
  220.             case NETWORK_TYPE_LTE:
  221.                 return true; // ~ 10+ Mbps
  222.             // Unknown
  223.             case TelephonyManager.NETWORK_TYPE_UNKNOWN:
  224.                 return false;
  225.             default:
  226.                 return false;
  227.             }
  228.         }else{
  229.             return false;
  230.         }
  231.     }
  232.        
  233.         /**
  234.          * IP转整型
  235.          * @param ip
  236.          * @return
  237.          */
  238.         public static long ip2int(String ip) {
  239.             String[] items = ip.split("\\.");
  240.             return Long.valueOf(items[0]) << 24
  241.                     | Long.valueOf(items[1]) << 16
  242.                     | Long.valueOf(items[2]) << 8 | Long.valueOf(items[3]);
  243.         }
  244.        
  245.         /**
  246.          * 整型转IP
  247.          * @param ipInt
  248.          * @return
  249.          */
  250.         public static String int2ip(long ipInt) {
  251.         StringBuilder sb = new StringBuilder();
  252.         sb.append(ipInt & 0xFF).append(".");
  253.         sb.append((ipInt >> 8) & 0xFF).append(".");
  254.         sb.append((ipInt >> 16) & 0xFF).append(".");
  255.         sb.append((ipInt >> 24) & 0xFF);
  256.         return sb.toString();
  257.         }

  258. }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值