Monitoring the Hotspot state in Android

不打扰是莪最后的温柔 提交于 2019-12-09 04:18:20

问题


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.



来源:https://stackoverflow.com/questions/14680978/monitoring-the-hotspot-state-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!