Question

I am to use a timer using timertask to check the wifi status after every minute in an android app. Here I have to check whether wifi radio is on or off after every minute. If the wifi radio is off I have to turn it on and when wifi radio is on the timer works fine as scheduled. But when wifi radio is turned off at the beginning or turned off while the app is running the scheduled task doesn't work as scheduled and it seems working quicker. What should I do to fix this?

      TimerTask timerTask = new TimerTask() {

            @Override
            public void run() {
                try {
                    ConnectivityManager connMgr = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);

                    NetworkInfo networkInfo     = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

                    if(!networkInfo.isAvailable()){                         
                        mainWifi.setWifiEnabled(true);
                    }
                    else{
                        // Wifi is available
                    }

                    if(networkInfo.isConnected()){
                        // Connected to a WiFi network.
                    }
                }
                catch(Exception e){

                }
            }
        };
        timerT.scheduleAtFixedRate(timerTask, 0, 60000);


Was it helpful?

Solution

Straight from the Android docs for Timer:

With fixed-rate execution, the start time of each successive run of a task is scheduled without regard for when the previous run took place. This may result in a series of bunched-up runs (one launched immediately after another) if delays prevent the timer from starting tasks on time.

It's impossible to explain the specific behavior you're observing without knowing a lot more about your code than you have posted, but the above is probably what's going on.

You probably want to be using fixed-period scheduling, which according to the docs, behaves more like what you seem to want:

With the default fixed-period execution, each successive run of a task is scheduled relative to the start time of the previous run, so two runs are never fired closer together in time than the specified period.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top