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

后端 未结 4 1547
无人共我
无人共我 2020-12-18 10:14

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 R         


        
相关标签:
4条回答
  • 2020-12-18 10:36

    Try this:

       LinearLayout.postDelayed(new Runnable() { 
            public void run() { 
    
            //Do stuff here
    
                // assuming LinearLayout is enclosing class
                LinearLayout.this.postDelayed(this, 2000);
            } 
       }, 2000);
    
    0 讨论(0)
  • 2020-12-18 10:43
     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 讨论(0)
  • 2020-12-18 10:55

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

    0 讨论(0)
  • 2020-12-18 10:56

    you can try a timer

    Here is another example

    0 讨论(0)
提交回复
热议问题