Android静态注册广播receiver检测WIFI连接状况变化



Android静态注册广播receiver检测WIFI连接状况变化

在AndroidManifest.xml静态注册一个receiver,增加对WiFi状态变化时候Android系统发送的广播事件过滤器,从而达到监听、检测WiFi状态变化。

 
            
                
                
            
        


完成相关广播接收器:

package zhangphil.wifi;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

public class WIFIStateChangedBroadcastReceiver extends BroadcastReceiver {

	private final String tag = "WIFI链接状况";

	@Override
	public void onReceive(Context context, Intent intent) {

		if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
			NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
			if (info.getState().equals(NetworkInfo.State.CONNECTED)) {

				WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
				WifiInfo wifiInfo = wifiManager.getConnectionInfo();

				// 当前WIFI名称
				Log.d(tag, "连接到WIFI " + wifiInfo.getSSID());
			}
		}

		if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
			int wifistate = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_DISABLED);

			if (wifistate == WifiManager.WIFI_STATE_DISABLED) {
				Log.d(tag, "WIFI关闭");
			}

			if (wifistate == WifiManager.WIFI_STATE_ENABLED) {
				Log.d(tag, "WIFI开启");
			}
		}
	}
}



增加权限:


    


附录相关文章:
【文章1】《Android判断设备是否打开WIFI、GPRS数据连接》链接地址:http://blog.csdn.net/zhangphil/article/details/43800909
【文章2】《Android检查设备是否联网》链接地址:http://blog.csdn.net/zhangphil/article/details/43795063


你可能感兴趣的:(Android)