Android WIFI狀態監控

第一類:有無wifi源及各個狀態間轉變

可監聽 WIFI_STATE_CHANGED_ACTION。(如下圖所示,雙擊圖片可放大)

  
有五種情況:
1-1 disabled
1-2 disabling
1-3 enable
1-4 enabling
1-5 unknown
 
可通過不同的Extra值,見下圖(雙擊可放大)獲得狀態常量:

代碼如下:
 

 

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.         }

 

摘自 小新專欄

發佈留言