Question

The timer task doesn't wait for the scheduled delayed time. I want to delay the network check by 10 seconds,but it performs the action within few seconds without waiting.Any help would be appreciated.

int i = 0;
public void timertask()
    {

        while(i < 5){

        Handler handler = new Handler(); 
        handler.postDelayed(new Runnable() {
                public void run() {
                if(isNetworkConnected()) // Some method to check net connection
                 {
                     download(); //Method to download
                 }
            }
        }, 10000);

        System.out.println("i  = "+i);
        i++;
        }

    }
Était-ce utile?

La solution

try this one.

TimerTask doAsynchronousTask;
    final Handler handler = new Handler();
    Timer timer = new Timer();

    doAsynchronousTask = new TimerTask() {

        @Override
        public void run() {

            handler.post(new Runnable() {
                public void run() {
                     if(isOnline){// check net connection
                     download(); //Method to download
                    }

                }
            });

        }

    };

    timer.schedule(doAsynchronousTask, 0, 10000);// execute in every 10 s
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top