Monitoring the Hotspot state in Android

2020-05-21 06:24发布

问题:

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

回答1:

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



回答2:

Hii #user802467 there is answer to your question asked in comment at this link : How to get wifi hotspot state. Values are between 10-13 because of version 4 and above. You can easily get the actual state as explained in the link.