zoukankan      html  css  js  c++  java
  • 网络监听以及判断网络是否可用

    网络监听:

    AndroidManifest中定义网络监听的receiver

    <receiver  
    
        android:name=".receiver.ConnectionChangeReceiver" >   
    
        <intent-filter>   
    
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>   
    
        </intent-filter>  
    
    </receiver>
    

      

    定义网路监听的广播接受类:

    public class ConnectionChangeReceiver extends BroadcastReceiver {
    
    	@Override
    	public void onReceive(Context context, Intent intent) {
    		if (!Utils.isNetworkConnected()) {
    			NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    			notificationManager.cancel(Constants.NOTIFICATION_SYNC);
    		}
    	}
    
    }
    

    判断网络是否可用:

    	public static boolean isNetworkConnected() {
    		ConnectivityManager connectivity = (ConnectivityManager) DoitApplication.mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    		if (connectivity == null) {
    			// TODO 网络不可用
    		} else {// 获取所有网络连接信息
    			NetworkInfo[] info = connectivity.getAllNetworkInfo();
    			if (info != null) {// 逐一查找状态为已连接的网络
    				for (int i = 0; i < info.length; i++) {
    					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
    						return true;
    					}
    				}
    			}
    		}
    		return false;
    	}
    

      


  • 相关阅读:
    CSS3实现轮播切换效果
    angularjs directive
    angularjs 迭代器
    anjularjs 路由
    sublime text3 快捷键设置
    如何使用git 跟进项目进程
    hdu 4842(NOIP 2005 过河)之 动态规划(距离压缩)
    叠箱子问题 之 动态规划
    华为oj 之 蜂窝小区最短距离
    华为oj 之 整数分隔
  • 原文地址:https://www.cnblogs.com/lilihuang/p/2181019.html
Copyright © 2011-2022 走看看