Search code examples
javaandroidmultithreadingandroid-wifi

Handling periodic checking of WiFi state within app


Newbie to Android app programming and I have a scenario that I'm struggling to code up in Android Studio.

My app requires the user be connected to a specific Wifi. So I'd like to periodically check the Wifi status and if it's not connected/ connected to the wrong Wifi, I want to throw up an AlertDialog till the user is connected to the correct Wifi.

However, I'm struggling with the implementation. My approach so far has been to have a method checkWifi() that tests if we're on the correct Wifi, and sets a global boolean onCorrectWifi accordingly. This checkWifi() runs periodically, every 30s via a TimerTask.

Within the same TimerTask as the checkWifi() method, is another method called handleWifiStatus(). The handleWifiStatus() method looks at onCorrectWifi and if it's True, does nothing. If onCorrectWifi is False, handleWifiStatus() spawns an AlertDialog and then enters a while loop. The while loop calls checkWifi() repeatedly until onCorrectWifi is True again, at which point the while loop is exited and the AlertDialog is dismissed and usual app activities resume.

I'm struggling with the actual implementation of this.

Am I making this too complicated for myself? Is there a better/ more simple implementation that'll achieve the whole "check Wifi state, if wrong, show AlertDialog till Wifi is good again" concept?


Solution

  • At first look, your methodology seems sound, so I'm not quite sure what's going wrong. That being said, Android actually has functionality in place to be notified when the network status changes to simplify exactly this scenario.

    // Retrieve the ConnectivityManager via the current Context
    ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    
    // Create the method to be called when the WiFi network changes
    ConnectivityManager.NetworkCallback callback = new ConnectivityManager.NetworkCallback() {
        @Override
        public void onAvailable(Network network) {
            // Check that this Network is the correct one and take
            // action as appropriate
        }
    };
    
    // Set the callback to be fired when WiFi status changes
    cm.registerNetworkCallback(
         new NetworkRequest.Builder()
         .addTransportType(TRANSPORT_WIFI)
         .build(),
         callback
    );