How to set timer in android?

后端 未结 21 923
渐次进展
渐次进展 2020-11-22 00:51

Can someone give a simple example of updating a textfield every second or so?

I want to make a flying ball and need to calculate/update the ball coordinates every se

21条回答
  •  心在旅途
    2020-11-22 01:25

    If you also need to run your code on UI thread (and not on timer thread), take a look on the blog: http://steve.odyfamily.com/?p=12

    public class myActivity extends Activity {
    private Timer myTimer;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
    
        myTimer = new Timer();
        myTimer.schedule(new TimerTask() {          
            @Override
            public void run() {
                TimerMethod();
            }
    
        }, 0, 1000);
    }
    
    private void TimerMethod()
    {
        //This method is called directly by the timer
        //and runs in the same thread as the timer.
    
        //We call the method that will work with the UI
        //through the runOnUiThread method.
        this.runOnUiThread(Timer_Tick);
    }
    
    
    private Runnable Timer_Tick = new Runnable() {
        public void run() {
    
        //This method runs in the same thread as the UI.               
    
        //Do something to the UI thread here
    
        }
    };
    }
    

提交回复
热议问题