Home » Android » android.net.wifi.STATE_CHANGE: not triggered on Wifi disconnect

android.net.wifi.STATE_CHANGE: not triggered on Wifi disconnect

Posted by: admin May 14, 2020 Leave a comment

Questions:

Is it normal to only have a broadcast intent with action NETWORK_STATE_CHANGED_ACTION (whose constant value is android.net.wifi.STATE_CHANGE) when a Wifi connection is coming back up? I.e. I don’t get this intent when Wifi is being disconnected.

UPDATE: I am mostly interested to >= 2.2 Froyo

How to&Answers:

public static final String
SUPPLICANT_CONNECTION_CHANGE_ACTION

Since: API Level 1

Broadcast intent
action indicating that a connection to
the supplicant has been established
(and it is now possible to perform
Wi-Fi operations) or the connection to
the supplicant has been lost. One
extra provides the connection state as
a boolean, where true means CONNECTED.

See Also

EXTRA_SUPPLICANT_CONNECTED

Constant Value: “android.net.wifi.supplicant.CONNECTION_CHANGE”

In android’s API it says that it’s not a good idea to check STATE_CHANGE for network connectivity and instead you should use SUPPLICANT_CONNECTION_CHANGE_ACTION. this will notice an establishment to a wifi network, and the disconnection of a wifi network. I don’t know if this might help you, but I do hope so. LINK

Answer:

I had a similar need in my project and ended up having to use both.

The android.net.wifi.supplicant.CONNECTION_CHANGE action sends a broadcast when the network is connected, but usually before the device has an IP address, so I needed the android.net.wifi.STATE_CHANGE action for that.

The android.net.wifi.STATE_CHANGE action receives a broadcast on disconnect only if the device is disconnecting from a network, but wifi is still enabled (when hotspot goes out of range, for example)

So you should put both actions for the receiver in the manifest:

<receiver android:name="net.moronigranja.tproxy.WifiReceiver">
            <intent-filter>
                    <action android:name="android.net.wifi.STATE_CHANGE"/>
                    <action android:name="android.net.wifi.supplicant.CONNECTION_CHANGE" />
            </intent-filter>
</receiver>

and you put an if to check which action is being called in the intent. Here is the onReceive method of the BroadcastReceiver in my code:

public void onReceive(Context c, Intent intent) {
      if(intent.getAction().equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)){ 
          boolean connected = intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false);
          if(!connected) {
               //Start service for disconnected state here
          }
      }

      else if(intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)){
          NetworkInfo netInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
          if( netInfo.isConnected() )
          {
              //Start service for connected state here.
          }   
      }
  }