简体   繁体   English

如何在Android上的Java中每两秒执行一次函数?

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

I'm trying to execute a chunk of Java code in my Android program every two seconds. 我试图每两秒在我的Android程序中执行一大块Java代码。 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. 在此先感谢您的帮助。

Try this: 尝试这个:

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

        //Do stuff here

            // assuming LinearLayout is enclosing class
            LinearLayout.this.postDelayed(this, 2000);
        } 
   }, 2000);
 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

Put your code in a loop. 将代码放在循环中。 Or you could look into Alarms . 或者您可以查看警报

you can try a timer 你可以尝试一下计时器

Here is another example 这是另一个例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM