Android Timer Task doesn't wait for the scheduled delayed time

折月煮酒 提交于 2019-12-11 08:19:26

问题


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

    }

回答1:


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


来源:https://stackoverflow.com/questions/9718165/android-timer-task-doesnt-wait-for-the-scheduled-delayed-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!