android.net.wifi.STATE_CHANGE: not triggered on Wifi disconnect

前端 未结 2 1989
渐次进展
渐次进展 2020-12-23 12:54

Is it normal to only have a broadcast intent with action NETWORK_STATE_CHANGED_ACTION (whose constant value is android.net.wifi.STATE_CHANGE) when

2条回答
  •  余生分开走
    2020-12-23 13:22

    I had a similar need in my project and ended up having to use both.

    The android.net.wifi.supplicant.CONNECTION_CHANGE action sends a broadcast when the network is connected, but usually before the device has an IP address, so I needed the android.net.wifi.STATE_CHANGE action for that.

    The android.net.wifi.STATE_CHANGE action receives a broadcast on disconnect only if the device is disconnecting from a network, but wifi is still enabled (when hotspot goes out of range, for example)

    So you should put both actions for the receiver in the manifest:

    
                
                        
                        
                
    
    

    and you put an if to check which action is being called in the intent. Here is the onReceive method of the BroadcastReceiver in my code:

    public void onReceive(Context c, Intent intent) {
          if(intent.getAction().equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)){ 
              boolean connected = intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false);
              if(!connected) {
                   //Start service for disconnected state here
              }
          }
    
          else if(intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)){
              NetworkInfo netInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
              if( netInfo.isConnected() )
              {
                  //Start service for connected state here.
              }   
          }
      }
    

提交回复
热议问题