Android - Correct way to detect disconnecting from a particular wifi ssid?

前端 未结 4 1990
梦毁少年i
梦毁少年i 2021-02-06 16:02

I\'ve seen a couple of BroadcastReciever examples to detect wifi disconnects but none of them seem to work correctly (triggering twice for each disconnect for example) and none

4条回答
  •  醉梦人生
    2021-02-06 16:42

    My code to detect (and rebroadcast) connections and disconnects (not by disabling wifi) and including the SSID as an extra is as follows. Most of what I've read suggested using SUPPLICANT_CONNECTION_CHANGE_ACTION but this just did not work correctly, it would seemingly only fire when disabling/enabling wifi on my device (Nexus 4) and not during connections. The only problem is on first run of the app as it won't record the current ssid so doesn't know what the ssid of the network that has just been connected. Any ideas around this?

    public class EventMapper extends BroadcastReceiver
    {
        private static String lastConnectedSsid = "";
    
        @Override
        public void onReceive(Context context, Intent intent)
        {
            if (intent.getAction().equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION))
            {
                SupplicantState state = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE);
    
                if(state == SupplicantState.COMPLETED)
                {
                    WifiManager manager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
    
                    lastConnectedSsid = manager.getConnectionInfo().getSSID().replace("\"", "");
    
                    Intent newIntent = new Intent();            
                    newIntent.setAction(Event.App_Event_WifiConnected.name());
                    newIntent.putExtra("App_Events_SSID", lastConnectedSsid);
    
                    context.sendBroadcast(newIntent);
                }
    
                if(state == SupplicantState.DISCONNECTED)
                {
                    boolean wifiEnabled = ((WifiManager)context.getSystemService(Context.WIFI_SERVICE)).isWifiEnabled();
    
                    if(wifiEnabled)
                    {
                        Intent newIntent = new Intent();            
                        newIntent.setAction(Event.App_Event_WifiDisconnected.name());
                        newIntent.putExtra("App_Events_SSID", lastConnectedSsid);
    
                        context.sendBroadcast(newIntent);   
                    }
                }
            }
        }
    }
    

提交回复
热议问题