开发者

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

开发者 https://www.devze.com 2023-03-03 10:02 出处:网络
I\'m trying to execute a chunk of Java code in my Android program every two seconds. My code currently looks like this:

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 he开发者_高级运维lp.


Try this:

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

        //Do stuff here

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


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


you can try a timer

Here is another example


 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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号