Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 mention checking against an ssid, is this even possible?

So just to clarify, I want to detect disconnection from a particular ssid. An actual disconnect and not wifi being disabled on the device.

Thanks

EDIT: Re-opening as nothing works on both the devices we have to test.

like image 821
SeeNoWeevil Avatar asked Jan 13 '23 18:01

SeeNoWeevil


1 Answers

NETWORK_STATE_CHANGED_ACTION was the answer in the end. The device having the problem registering this event started working when another app (which would also be listening for similar events) was uninstalled! No idea how or why an app could block events registering with another app. The final solution ended up being;

    String action = intent.getAction();

    if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION))
    {
        WifiManager manager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
        NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
        NetworkInfo.State state = networkInfo.getState();

        if(state == NetworkInfo.State.CONNECTED)
        {
            String connectingToSsid = manager.getConnectionInfo().getSSID().replace("\"", "");
            WifiStateHistory.recordConnectedSsid(connectingToSsid);
//connected
        }

        if(state == NetworkInfo.State.DISCONNECTED)
        {
            if(manager.isWifiEnabled())
            {
                String disconnectedFromSsid = WifiStateHistory.getLastConnectedSsid();
//disconnected
            }
        }
    }
like image 159
SeeNoWeevil Avatar answered Jan 30 '23 20:01

SeeNoWeevil