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

    一.   ConnectivityManager详解

     概要

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

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

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

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

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


     比较重要的几个类常量

int TYPE_BLUETOOTH The Bluetooth data connection. 蓝牙数据连接
int TYPE_ETHERNET The Ethernet data connection. 以太网数据连接
int TYPE_MOBILE The Mobile data connection. 移动数据链接
int TYPE_WIFI The WIFI data connection. wifi链接
String CONNECTIVITY_ACTION 网络连接发生改变
int DEFAULT_NETWORK_PREFERENCE 默认网络连接偏好,建议在config.xml中进行配置.并通过调用 getNetworkPreference() 获取应用的当前设置值。
String EXTRA_EXTRA_INFO The lookup key for a string that provides optionally supplied extra information about the network state.
查询关键字,提供关于网络状态的信息
String EXTRA_NETWORK_INFO  建议使用getActiveNetworkInfo() or getAllNetworkInfo()获取网络连接信息
String EXTRA_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.

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

public class NetWorkUtil {
	private static String LOG_TAG = "<span style="font-family: Arial, Helvetica, sans-serif;">NetWorkUtil</span><span style="font-family: Arial, Helvetica, sans-serif;">";</span>

	public static boolean isNetworkAvailable(Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		if (connectivity == null) {
			Log.w(LOG_TAG, "无法获得ConnectivityManager");
		} else {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].isAvailable()) {
						return true;
					}
				}
			}
		}
		return false;
	}
	
	public static boolean checkNetState(Context context){
    	        boolean netstate = false;
		ConnectivityManager connectivity = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
		if(connectivity != null)
		{
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++)
				{
					if (info[i].getState() == NetworkInfo.State.CONNECTED) 
					{
						netstate = true;
						break;
					}
				}
			}
		}
		return netstate;
        }
	
	public static boolean isNetworkRoaming(Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity == null) {
			Log.w(LOG_TAG, "couldn't get connectivity manager");
		} else {
			NetworkInfo info = connectivity.getActiveNetworkInfo();
			if (info != null
					&& info.getType() == ConnectivityManager.TYPE_MOBILE) {
				TelephonyManager tm = (TelephonyManager) context
						.getSystemService(Context.TELEPHONY_SERVICE);
				if (tm != null && tm.isNetworkRoaming()) {
					return true;
				} else {
				}
			} else {
			}
		}
		return false;
	}

	public static boolean isMobileDataEnable(Context context) throws Exception {
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		boolean isMobileDataEnable = false;

		isMobileDataEnable = connectivityManager.getNetworkInfo(
				ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();

		return isMobileDataEnable;
	}

	public static boolean isWifiDataEnable(Context context) throws Exception {
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		boolean isWifiDataEnable = false;
		isWifiDataEnable = connectivityManager.getNetworkInfo(
				ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
		return isWifiDataEnable;
	}
}


       

    



你可能感兴趣的:(Android网络编程(二)ConnectivityManager和NetworkInfo详解)