1

定时器任务不会等待预定的延迟时间。我想将网络检查延迟 10 秒,但它会在几秒钟内执行操作而无需等待。任何帮助将不胜感激。

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++;
        }

    }
4

1 回答 1

1

试试这个。

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
于 2012-03-15T11:02:57.517 回答