0

What is a way to listen and receive an event when Wifi is enabled or disabled on Android?

Note that I am not looking for connectivity to the internet. I am just looking for an event which says wifi in the wifi settings was enabled.

AdeleGoldberg
  • 1,289
  • 3
  • 12
  • 28

1 Answers1

0

Use WIFI_STATE_CHANGED_ACTION broadcast intent action to check Wi-Fi state.

Add this to your manifest file:

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

And use this class for receiving broadcast:

public class WifiReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // Check the state here
        int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, -1);
    }
}
Saurabh Thorat
  • 18,131
  • 5
  • 53
  • 70
  • How do you check wifi state inside `onReceive`? Is it possible to do this without writing a new class changing the inheritance hierarchy of my class? – AdeleGoldberg Sep 25 '19 at 08:14
  • 1
    I have edited my answer to check state in `onReceive()` using [this](https://developer.android.com/reference/android/net/wifi/WifiManager.html#EXTRA_WIFI_STATE) key. And you would have to make a BroadcastReceiver class to get that broadcast. – Saurabh Thorat Sep 25 '19 at 08:17
  • this won't work if the receiver is used in the manifest because the intent isn't whitelisted, only a runtime receiver can receive it – greywolf82 Sep 25 '19 at 11:55