Android网络编程(二)ConnectivityManager和NetworkInfo详解

来源:互联网 发布:淘宝 app 版本 编辑:程序博客网 时间:2024/05/22 02:16


   

Android网络编程ConnectivityManagerNetworkInfo

    一.   ConnectivityManager详解

     概要

     ConnectivityManager是网络连接相关的管理器,它主要用于查询网络状态并在网络发生改变时发出状态变化通知。这个类主要负责的下列四个方面:

     1.  监控网络状态(包括WiFi, GPRS, UMTS等)。

     2.  当网络连接改变时发送广播Intent。

     3.  当一种网络断开时,试图连接到另一种网络进行故障处理。

     4.  提供一系列接口让应用程序查询可获得的网络的粗粒度和细粒度状态。 


     比较重要的几个类常量

intTYPE_BLUETOOTHThe Bluetooth data connection. 蓝牙数据连接intTYPE_ETHERNETThe Ethernet data connection. 以太网数据连接intTYPE_MOBILEThe Mobile data connection. 移动数据链接intTYPE_WIFIThe WIFI data connection. wifi链接StringCONNECTIVITY_ACTION网络连接发生改变intDEFAULT_NETWORK_PREFERENCE默认网络连接偏好,建议在config.xml中进行配置.并通过调用 getNetworkPreference() 获取应用的当前设置值。StringEXTRA_EXTRA_INFOThe lookup key for a string that provides optionally supplied extra information about the network state.
查询关键字,提供关于网络状态的信息StringEXTRA_NETWORK_INFO 建议使用getActiveNetworkInfo() or getAllNetworkInfo()获取网络连接信息StringEXTRA_NETWORK_TYPE触发 CONNECTIVITY_ACTION广播的网络类型

   

      比较重要的方法

NetworkInfo
getActiveNetworkInfo() 获取当前连接可用的网络
NetworkInfo[]
getAllNetworkInfo() 获取设备支持的所有网络类型的链接状态信息。
NetworkInfo
getNetworkInfo(int networkType)  获取特定网络类型的链接状态信息
int
getNetworkPreference()  获取当前偏好的网络类型。
boolean
isActiveNetworkMetered() 
Returns if the currently active data network is metered.
static boolean
isNetworkTypeValid(int networkType)   判断给定的数值是否表示一种网络
boolean
requestRouteToHost(int networkType, int hostAddress)
Ensure that a network route exists to deliver traffic to the specified host via the specified network interface.
void
setNetworkPreference(int preference)
Specifies the preferred network type.
int
startUsingNetworkFeature(int networkType, String feature)
Tells the underlying networking system that the caller wants to begin using the named feature.
int
stopUsingNetworkFeature(int networkType, String feature)
Tells the underlying networking system that the caller is finished using the named feature.

     

 二. NetworkInfo详解

        NetworkInfo是一个描述网络状态的接口,可通过ConnectivityManager调用getActiveNetworkInfo()获得当前连接的网络类型。

        NetworkInfo有两个枚举类型的成员变量NetworkInfo.DetailedState和NetworkInfo.State,用于查看当前网络的状态。其中NetworkInfo.State的值包括:

NetworkInfo.State CONNECTED 

已连接
NetworkInfo.State CONNECTING 
正在连接
NetworkInfo.State DISCONNECTED 

NetworkInfo.State DISCONNECTING 

NetworkInfo.State SUSPENDED 

NetworkInfo.State UNKNOWN 

        NetworkInfo.DetailedState则状态描述更为详细。

   

        NetworkInfo还包括一系列可用的方法用于判断当前网络是否可用,如下:

Public Methods

NetworkInfo.DetailedState
getDetailedState()
Reports the current fine-grained state of the network.
String
getExtraInfo()
Report the extra information about the network state, if any was provided by the lower networking layers., if one is available.
String
getReason()  如果数据网络连接可用,但是连接失败,则通过此方法可获得尝试链接失败的原因
Report the reason an attempt to establish connectivity failed, if one is available.
NetworkInfo.State
getState()  获取网络连接的粗粒度状态
Reports the current coarse-grained state of the network.
int
getSubtype()  
Return a network-type-specific integer describing the subtype of the network.
String
getSubtypeName()
Return a human-readable name describing the subtype of the network.
int
getType()报告当前网络从属的网络类型
Reports the type of network to which the info in this NetworkInfo pertains.
String
getTypeName()报告当前网络从属的网络类型,更明确的方式如wifi,和mobile等。
Return a human-readable name describe the type of the network, for example "WIFI" or "MOBILE".
boolean
isAvailable()  判断当前网络是否可用
Indicates whether network connectivity is possible.
boolean
isConnected()  判断当前网络是否存在,并可用于数据传输
Indicates whether network connectivity exists and it is possible to establish connections and pass data.
boolean
isConnectedOrConnecting()  
Indicates whether network connectivity exists or is in the process of being established.
boolean
isFailover()
Indicates whether the current attempt to connect to the network resulted from the ConnectivityManager trying to fail over to this network following a disconnect from another network.
boolean
isRoaming()  判断设备当前是否在网络上漫游
Indicates whether the device is currently roaming on this network.
String
toString()  返回一个包含该网络的简单的易懂的字符串描述。
Returns a string containing a concise, human-readable description of this object.

          一般来说很少需要用到所有的内容。最后奉上一点点干货:

[java] view plaincopyprint?
  1. public class NetWorkUtil {  
  2.     private static String LOG_TAG = "<span style="font-family: Arial, Helvetica, sans-serif;">NetWorkUtil</span><span style="font-family: Arial, Helvetica, sans-serif;">";</span>  
  3.   
  4.     public static boolean isNetworkAvailable(Context context) {  
  5.         ConnectivityManager connectivity = (ConnectivityManager) context  
  6.                 .getSystemService(Context.CONNECTIVITY_SERVICE);  
  7.   
  8.         if (connectivity == null) {  
  9.             Log.w(LOG_TAG, "无法获得ConnectivityManager");  
  10.         } else {  
  11.             NetworkInfo[] info = connectivity.getAllNetworkInfo();  
  12.             if (info != null) {  
  13.                 for (int i = 0; i < info.length; i++) {  
  14.                     if (info[i].isAvailable()) {  
  15.                         return true;  
  16.                     }  
  17.                 }  
  18.             }  
  19.         }  
  20.         return false;  
  21.     }  
  22.       
  23.     public static boolean checkNetState(Context context){  
  24.                 boolean netstate = false;  
  25.         ConnectivityManager connectivity = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);  
  26.         if(connectivity != null)  
  27.         {  
  28.             NetworkInfo[] info = connectivity.getAllNetworkInfo();  
  29.             if (info != null) {  
  30.                 for (int i = 0; i < info.length; i++)  
  31.                 {  
  32.                     if (info[i].getState() == NetworkInfo.State.CONNECTED)   
  33.                     {  
  34.                         netstate = true;  
  35.                         break;  
  36.                     }  
  37.                 }  
  38.             }  
  39.         }  
  40.         return netstate;  
  41.         }  
  42.       
  43.     public static boolean isNetworkRoaming(Context context) {  
  44.         ConnectivityManager connectivity = (ConnectivityManager) context  
  45.                 .getSystemService(Context.CONNECTIVITY_SERVICE);  
  46.         if (connectivity == null) {  
  47.             Log.w(LOG_TAG, "couldn't get connectivity manager");  
  48.         } else {  
  49.             NetworkInfo info = connectivity.getActiveNetworkInfo();  
  50.             if (info != null  
  51.                     && info.getType() == ConnectivityManager.TYPE_MOBILE) {  
  52.                 TelephonyManager tm = (TelephonyManager) context  
  53.                         .getSystemService(Context.TELEPHONY_SERVICE);  
  54.                 if (tm != null && tm.isNetworkRoaming()) {  
  55.                     return true;  
  56.                 } else {  
  57.                 }  
  58.             } else {  
  59.             }  
  60.         }  
  61.         return false;  
  62.     }  
  63.   
  64.     public static boolean isMobileDataEnable(Context context) throws Exception {  
  65.         ConnectivityManager connectivityManager = (ConnectivityManager) context  
  66.                 .getSystemService(Context.CONNECTIVITY_SERVICE);  
  67.         boolean isMobileDataEnable = false;  
  68.   
  69.         isMobileDataEnable = connectivityManager.getNetworkInfo(  
  70.                 ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();  
  71.   
  72.         return isMobileDataEnable;  
  73.     }  
  74.   
  75.     public static boolean isWifiDataEnable(Context context) throws Exception {  
  76.         ConnectivityManager connectivityManager = (ConnectivityManager) context  
  77.                 .getSystemService(Context.CONNECTIVITY_SERVICE);  
  78.         boolean isWifiDataEnable = false;  
  79.         isWifiDataEnable = connectivityManager.getNetworkInfo(  
  80.                 ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();  
  81.         return isWifiDataEnable;  
  82.     }  
  83. }  

0 0
原创粉丝点击