不要以为Wifi的状态只有2个!
Android下Wifi的状态实际上有5个,依次为:
0 --> WIFI_STATE_DISABLING
1 --> WIFI_STATE_DISABLED
2 --> WIFI_STATE_ENABLING
3 --> WIFI_STATE_ENABLED
4 --> WIFI_STATE_UNKNOWN
每当该状态有变化时,系统都会发出“WIFI_STATE_CHANGED_ACTION”广播事件。
以下的receiver仅供参考:
(注册过程如下:
mWifiStateReceiver = new WifiStateReceiver();
registerReceiver(mWifiStateReceiver, new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
注销过程:
unregisterReceiver(mWifiStateReceiver);
)
class WifiStateReceiver extends BroadcastReceiver {
public void onReceive(Context c, Intent intent) {
Bundle bundle = intent.getExtras();
int oldInt = bundle.getInt("previous_wifi_state");
int newInt = bundle.getInt("wifi_state");
String oldStr = (oldInt>=0 && oldInt<WIFI_STATES.length) ?WIFI_STATES[oldInt] :"?";
String newStr = (newInt>=0 && oldInt<WIFI_STATES.length) ?WIFI_STATES[newInt] :"?";
Log.e(TAG, "oldS="+oldStr+", newS="+newStr);
if(newInt==WifiManager.WIFI_STATE_DISABLED || newInt==WifiManager.WIFI_STATE_ENABLED) {
onWifiStateChange(); // define this function elsewhere!
} else if(newInt==WifiManager.WIFI_STATE_DISABLING ||
newInt==WifiManager.WIFI_STATE_ENABLING)
{
chkbox_wifi.setText(newStr);
} else {
newStr += " (Is wpa_supplicant.conf readable?)";
chkbox_wifi.setText(newStr);
}
}
}
// 显示Wifi状态以及ip地址:
public static String StringizeIp(int ip) {
int ip4 = (ip>>24) & 0x000000FF;
int ip3 = (ip>>16) & 0x000000FF;
int ip2 = (ip>> 8 )& 0x000000FF;
int ip1 = ip & 0x000000FF;
return Integer.toString(ip1) + "." + ip2 + "." + ip3 + "." + ip4;
}
private void onWifiStateChange() {
String ip_str = "";
WifiInfo info = mMainWifi.getConnectionInfo();
if(info != null) {
int ipaddr = info.getIpAddress();
ip_str = " (ip="+StringizeIp(ipaddr)+")";
}
if(mMainWifi.isWifiEnabled()==true)
chkbox_wifi.setText("Wifi is on [" + ip_str + "]");
else
chkbox_wifi.setText("Wifi is off");
}
很多google出来的代码并未提及wifi的五个状态,实际上这在文档中说得很清楚。如果以为只有2个状态,那么,不仅状态监视会出问题,而且可能在监视到状态变化时作出错误的行为(你的onReceive()函数是否类似于多调用了几次?)。
原文地址:http://blog.sina.com.cn/s/blog_3e3fcadd0100n8rc.html