Search code examples
androidandroid-intentbroadcastreceiver

Monitoring the Hotspot state in Android


I'm new to android.
I want to receive information via broadcastreceiver (onReceive) to know that if user enable/disable "Portable Wi-Fi Hotspot" (Settings->Wireless &Networks->Tethering & portable hotspot).
Check this link And I found that there is "android.net.wifi.WIFI_AP_STATE_CHANGED" but it was set to hidden. Any how I can use that ???

Thanks in advance


Solution

  • to receive enable/disable "Portable Wi-Fi Hotspot" events you will need to register an Receiver for WIFI_AP_STATE_CHANGED as :

    mIntentFilter = new IntentFilter("android.net.wifi.WIFI_AP_STATE_CHANGED");
    registerReceiver(mReceiver, mIntentFilter);
    

    inside BroadcastReceiver onReceive we can extract wifi Hotspot state using wifi_state as :

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if ("android.net.wifi.WIFI_AP_STATE_CHANGED".equals(action)) {
    
                 // get Wi-Fi Hotspot state here 
                int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
    
                if (WifiManager.WIFI_STATE_ENABLED == state % 10) {
                    // Wifi is enabled
                }
    
            }
        }
    };
    

    you can do same by declaring Receiver in AndroidManifest for android.net.wifi.WIFI_AP_STATE_CHANGED action and also include all necessary wifi permissions in AndroidManifest.xml

    EDIT :

    Add receiver in AndroidManifest as :

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

    you can see this example for more help