SystemService 学习笔记之ConnectivityManager


ConnectivityManager功能:监视网络连接状态

通过context.getSystemService(Context.CONNECTIVITY_SERVICE);方法获取,

需要添加权限 :android.permission.ACCESS_NETWORK_STATE

常用方法:

1.getAllNetworkInfo() //获取所有网络连接信息

2.getActiveNetworkInfo()// 获取正连接的网络的信息

3.getNetworkInfo(int networkType)//获取指定的网络连接类型的信息

    networkType的类型有:ConnectivityManage.TYPE_WIFI;ConnectivityManage.TYPE_MOBILE 等

getAllNetworkInfo()实例:

	public static boolean isNetworkAvailable(Activity mActivity){
		Context context = mActivity.getApplicationContext();
		
		ConnectivityManager connectivity = (ConnectivityManager)context.getSystemService(
				Context.CONNECTIVITY_SERVICE);
		
		if(connectivity == null){
			return false;
		}else {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if(info != null ){
				for(int i=0; i

getActiveNetworkInfo()实例:

	  public static boolean isNetworkAvailable(Activity mActivity){
		  Context context = mActivity.getApplicationContext();

		  ConnectivityManager connectivity = (ConnectivityManager)context.getSystemService(
		  Context.CONNECTIVITY_SERVICE);
		  NetworkInfo networkInfo = connectivity.getActiveNetworkInfo();  
		   // 获取当前的网络连接是否可用  
		    //网络类型的判断networkInfo.getType()==ConnectivityManager.TYPE_MOBILE
		  	if(networkInfo.isAvailable())
		  		return true;
		  	else
		  		return false;

 getNetworkInfo(int networkType)实例:

	public static boolean isNetworkAvailable(Activity mActivity){
	Context context = mActivity.getApplicationContext();
		  			
	ConnectivityManager connectivity = (ConnectivityManager)context.getSystemService(
		  	Context.CONNECTIVITY_SERVICE);
	if(State.CONNECTED==connectivity.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState())
		  	return true;
	if(State.CONNECTED==connectivity.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState())
		  return true;
	else	  			  
	    return false;
		  			
		  		}

  State的六种状态:
 public static final NetworkInfo.State CONNECTED

 public static final NetworkInfo.State CONNECTING

 public static final NetworkInfo.State DISCONNECTED

 public static final NetworkInfo.State DISCONNECTING

 public static final NetworkInfo.State SUSPENDED

 public static final NetworkInfo.State UNKNOWN



你可能感兴趣的:(SystemService 学习笔记之ConnectivityManager)