Search code examples
androidandroid-intentservicewifi

Execute code when wifi SSID changes


I would like to perform some actions when the SSID of the wireless network the phone is connected to changes. This should also work if the phone is "inactive" (e.g. locked).

Is a service the right type of application for this? I guess Android makes it possible for my service to get called on such events? How would I do that?


Solution

  • Create a BroadcastReceiver listening for WifiManager.NETWORK_STATE_CHANGED_ACTION, grab the SSID from the intent extra WifiManager.EXTRA_BSSID inside onReceive.

    If your SSID processing work is expensive, offload it to a service (see the docs for BroadcastReceiver.onReceive).

    Your AndroidManifest.xml should look something like:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        ...>
    
        <!-- Permission to listen for network changes -->
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    
        <application
            ...>
            <receiver android:name=".YourBroadcastReceiver" >
                <intent-filter>
                    <action android:name="android.net.wifi.STATE_CHANGE" />
                </intent-filter>
            </receiver>
        </application>
    </manifest>