回调以及动态注册广播

需求实现:activity内注册broadcastReceiver,broadcastReceiver接收到广播后,调用activity里边的方法。

eg:网络链接状态改变后,刷新界面。

1.写自己的receiver:

/**
 * 监听wifi链接变化
 * @author fhzm
 *
 */
public class WifiReceiver extends BroadcastReceiver{
	
	private WifiStateListener wifiStateListener;

	@Override
	public void onReceive(Context context, Intent intent) {
		 // 这个监听网络连接的设置,包括wifi和移动数据的打开和关闭。.
        // 最好用的还是这个监听。wifi如果打开,关闭,以及连接上可用的连接都会接到监听
        // 这个广播的最大弊端是比上边两个广播的反应要慢,如果只是要监听wifi,我觉得还是用上边两个配合比较合适
        if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
            ConnectivityManager manager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo activeNetwork = manager.getActiveNetworkInfo();
            if (activeNetwork != null) { // connected to the internet
                if (activeNetwork.isConnected()) {
                    if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
                        //"当前WiFi连接可用 "
                    	wifiStateListener.WifiSate(1);
                    } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
                        //"当前移动网络连接可用 "
                    	wifiStateListener.WifiSate(1);
                    }
                } else {
                    // "当前没有网络连接,请确保你已经打开网络 "
                	wifiStateListener.WifiSate(0);
                }
            } else {   // not connected to the internet
            	wifiStateListener.WifiSate(0);
                //"当前没有网络连接,请确保你已经打开网络 "
            }
        }
	}
	
	public interface WifiStateListener{
		public void WifiSate(int state);
	}
	
	public void setWifiStateListener(WifiStateListener wifiStateListener) {
		this.wifiStateListener = wifiStateListener; 
	}

}

2.在manifest文件中注册

<receiver android:name="com.xxx.xxx.receiver.WifiReceiver" >
        </receiver>

3.在activity中:

/**
	 * 监听wifi链接状态
	 */
	private void setWifiListener() {
		WifiReceiver wifiReceiver = new WifiReceiver();
		IntentFilter intentFilter = new IntentFilter(); 
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); 
		wifiReceiver.setWifiStateListener(new WifiStateListener() {
			@Override
			public void WifiSate(int state) {
				if(state == 1){//网络链接成功
					initData();
					wifiConnState = true;
				}else{//网络无链接
					wifiConnState = false;
				}
			}
		});
		registerReceiver(wifiReceiver,intentFilter);
	}


阅读更多
个人分类: 逻辑
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭