How to execute a function every two seconds in Java on Android?

余生长醉 提交于 2019-11-28 01:24:46

问题


I'm trying to execute a chunk of Java code in my Android program every two seconds. My code currently looks like this:

       LinearLayout.postDelayed(new Runnable() { 
            public void run() { 

            //Do stuff here

            } 
       }, 2000);

Unfortunately, this only runs once after two seconds and then never runs again. How could I get it to run every two seconds?

Thanks in advance for all your help.


回答1:


Try this:

   LinearLayout.postDelayed(new Runnable() { 
        public void run() { 

        //Do stuff here

            // assuming LinearLayout is enclosing class
            LinearLayout.this.postDelayed(this, 2000);
        } 
   }, 2000);



回答2:


Put your code in a loop. Or you could look into Alarms.




回答3:


you can try a timer

Here is another example




回答4:


 new Timer().scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            // Enter your code which you want to execute every 2 second
        }
    }, 0, 2000);//put here time 1000 milliseconds = 1 second


来源:https://stackoverflow.com/questions/5902600/how-to-execute-a-function-every-two-seconds-in-java-on-android

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