How to set timer in android?

后端 未结 21 905
渐次进展
渐次进展 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:36

    I Abstract Timer away and made it a separate class:

    Timer.java

    import android.os.Handler;
    
    public class Timer {
    
        IAction action;
        Handler timerHandler = new Handler();
        int delayMS = 1000;
    
        public Timer(IAction action, int delayMS) {
            this.action = action;
            this.delayMS = delayMS;
        }
    
        public Timer(IAction action) {
            this(action, 1000);
        }
    
        public Timer() {
            this(null);
        }
    
        Runnable timerRunnable = new Runnable() {
    
            @Override
            public void run() {
                if (action != null)
                    action.Task();
                timerHandler.postDelayed(this, delayMS);
            }
        };
    
        public void start() {
            timerHandler.postDelayed(timerRunnable, 0);
        }
    
        public void stop() {
            timerHandler.removeCallbacks(timerRunnable);
        }
    }
    

    And Extract main action from Timer class out as

    IAction.java

    public interface IAction {
        void Task();
    }
    

    And I used it just like this:

    MainActivity.java

    public class MainActivity extends Activity implements IAction{
    ...
    Timer timerClass;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
            ...
            timerClass = new Timer(this,1000);
            timerClass.start();
            ...
    }
    ...
    int i = 1;
    @Override
    public void Task() {
        runOnUiThread(new Runnable() {
    
            @Override
            public void run() {
                timer.setText(i + "");
                i++;
            }
        });
    }
    ...
    }
    

    I Hope This Helps

提交回复
热议问题