WIFI状态的获取及监听
- 在Activit获取wifi状态
获取WIFI的开关状态
WifiManager wifiMgr = (WifiManager) this.getSystemService(WIFI_SERVICE); int stat = wifiMgr.getWifiState(),
获取WIFI的连接状态
ConnectivityManager conMan = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE); State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
- 监听wifi状态
监听WIFI状态处理类
public class WifiStateReceiver extends BroadcastReceiver { @Override public void onReceive(Context arg0, Intent intent) { // WIFI的开关状态处理 if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())) { int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0); switch (wifiState) { case WifiManager.WIFI_STATE_ENABLED: case WifiManager.WIFI_STATE_ENABLING: // 处于要启用的状态 break; case WifiManager.WIFI_STATE_DISABLED: case WifiManager.WIFI_STATE_DISABLING: // 处于要停用的状态 break; } } // WIFI的连接状态处理 if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) { Parcelable parcelable = intent .getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); if (parcelable instanceof NetworkInfo) { NetworkInfo networkInfo = (NetworkInfo) parcelable; switch (networkInfo.getState()) { case CONNECTED: // TODO 连接上后的处理 break; case CONNECTING: case DISCONNECTING: case SUSPENDED: case UNKNOWN: // TODO 非连接上的处理 break; } } } // WIFI详细信息获取 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) { NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO); } } }
AndroidManifest.xml的Pemisstion页添加权限
ACCESS_WIFI_STATE
ACCESS_NETWORK_STATE
AndroidManifest.xml的Application页,在Application Notes区域点击Add,选择Receiver
在Application页Attributes for Receiver区域,设置
Name属性为刚写的Receiver类WifiStateReceiver
再为WifiStateReceiver节点添加Intent Filter
再在intent-filters下添加下面三个Action
android.net.wifi.WIFI_STATE_CHANGED
android.net.wifi.STATE_CHANGE
android.net.wifi.supplicant.CONNECTION_CHANGE