Android WIFI状态监控

第一类:有无wifi源及各个状态间转变

可监听 WIFI_STATE_CHANGED_ACTION。(如下图所示,双击图片可放大)

  Android WIFI状态监控_第1张图片
有五种情况:
1-1 disabled
1-2 disabling
1-3 enable
1-4 enabling
1-5 unknown
 
可通过不同的Extra值,见下图(双击可放大)获得状态常量:
Android WIFI状态监控_第2张图片
代码如下:
 

 

1. if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) {//在此监听wifi有无
2.             int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
3.             
4.             switch (wifiState) {
5.             case WifiManager.WIFI_STATE_DISABLED:
6.                 updateWifiStatus(R.drawable.wifi_disable);
7.                 Toast.makeText(mContext, R.string.wifi_disable,
8.                         Toast.LENGTH_LONG).show();
9.                 break;
10.             case WifiManager.WIFI_STATE_DISABLING:
11.                 break;
12.             case WifiManager.WIFI_STATE_ENABLED:
13.                 updateWifiStatus(R.drawable.wifi_enable);
14.                 Toast.makeText(mContext, R.string.wifi_enable,
15.                         Toast.LENGTH_LONG).show();
16.                 break;
17.             case WifiManager.WIFI_STATE_ENABLING:
18.                 break;
19.             case WifiManager.WIFI_STATE_UNKNOWN:
20.                 break;
21.             }
22.         } 
 
也可通过以下代码实现:
1. //另外一种方式
2.         mWifiMng = (WifiManager) mContext
3.                 .getSystemService(mContext.WIFI_SERVICE);
4.         
5.         switch (mWifiMng.getWifiState()) {
6.         case WifiManager.WIFI_STATE_DISABLED:
7.             updateWifiStatus(R.drawable.wifi_disable);
8.             Toast.makeText(mContext, R.string.wifi_disable,
9.                     Toast.LENGTH_LONG).show();
10.             break;
11.         case WifiManager.WIFI_STATE_DISABLING:
12.             break;
13.         case WifiManager.WIFI_STATE_ENABLED:
14.             updateWifiStatus(R.drawable.wifi_enable);
15.             Toast.makeText(mContext, R.string.wifi_enable,
16.                     Toast.LENGTH_LONG).show();
17.             break;
18.         case WifiManager.WIFI_STATE_ENABLING:
19.             break;
20.         case WifiManager.WIFI_STATE_UNKNOWN:
21.             break;
22.         }
 
第二类:wifi是否连接正常
 
可监听:NETWORK_STATE_CHANGED_ACTION(如下图所示,双击图片可放大)

  
有两种状况:
2-1连接
2-1未连接
在OnReceiver方法中,通过不同Extra值,获得连接状况,如下图,双击图片放大:

代码如下: 
 
 

1. if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) { 
2.             Parcelable parcelableExtra = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); 
3.             if (null != parcelableExtra) { 
4.                 NetworkInfo networkInfo = (NetworkInfo) parcelableExtra; 
5.                 boolean isConnected = networkInfo.isAvailable(); 
6.                 updateNetworkStatus(); 
7.             } 
8.         }

 


你可能感兴趣的:(Android WIFI状态监控)