How to get wifi hotspot state

前端 未结 4 835
我寻月下人不归
我寻月下人不归 2021-01-06 00:54

I am creating wifi hotspot in my phone and I want get its state change event when I switched on or off hotspot.

4条回答
  •  醉酒成梦
    2021-01-06 01:02

    To get the current state of the hotspot AP, I use:

    final WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    final int apState = (Integer) wifiManager.getClass().getMethod("getWifiApState").invoke(wifiManager);
    
    if (apState == 13) {
        // Ap Enabled
    }
    

    And to get updates when the hotspot AP gets enabled/disabled, receive the "android.net.wifi.WIFI_AP_STATE_CHANGED" intent in a BroadcastReceiver:

    public class WifiAPReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction() == "android.net.wifi.WIFI_AP_STATE_CHANGED") {
                int apState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
                if (apState == 13) {
                    // Hotspot AP is enabled
                } else {
                    // Hotspot AP is disabled/not ready
                }
            }
        }
    }
    

    Also, don't forget your declaration and permissions in the Manifest:

    
        
            
        
    
    
    
    

提交回复
热议问题