Category 1: whether there is a wifi source or not and the status changes
You can listen to WIFI_STATE_CHANGED_ACTION. (As shown in, double-click an image to enlarge it)
There are five situations:
1-1 disabled
1-2 disabling
1-3 enable
1-4 enabling
1-5 unknown
You can use different Extra values. For details, see (double-click to enlarge) to obtain status constants:
The Code is as follows:
1. if (WifiManager. WIFI_STATE_CHANGED_ACTION.equals (action) {// whether wifi is monitored here
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 .}
You can also use the following code:
1. // ANOTHER METHOD
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 .}
Category 2: whether the Wi-Fi connection is normal
Listener: NETWORK_STATE_CHANGED_ACTION (as shown in, double-click the image to enlarge it)
There are two situations:
2-1 Connection
2-1 not connected
In the OnReceiver method, use different Extra values to obtain the connection status, for example, double-click the image to enlarge:
The Code is as follows:
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 .}
From xiaoxin's column