How to set a timer in android

前端 未结 13 1844
天命终不由人
天命终不由人 2020-11-22 06:43

What is the proper way to set a timer in android in order to kick off a task (a function that I create which does not change the UI)? Use this the Java way: http://docs.ora

13条回答
  •  一个人的身影
    2020-11-22 07:01

    I am using a handler and runnable to create a timer. I wrapper this in an abstract class. Just derive/implement it and you are good to go:

     public static abstract class SimpleTimer {
        abstract void onTimer();
    
        private Runnable runnableCode = null;
        private Handler handler = new Handler();
    
        void startDelayed(final int intervalMS, int delayMS) {
            runnableCode = new Runnable() {
                @Override
                public void run() {
                    handler.postDelayed(runnableCode, intervalMS);
                    onTimer();
                }
            };
            handler.postDelayed(runnableCode, delayMS);
        }
    
        void start(final int intervalMS) {
            startDelayed(intervalMS, 0);
        }
    
        void stop() {
            handler.removeCallbacks(runnableCode);
        }
    }
    

    Note that the handler.postDelayed is called before the code to be executed - this will make the timer more closed timed as "expected". However in cases were the timer runs to frequently and the task (onTimer()) is long - there might be overlaps. If you want to start counting intervalMS after the task is done, move the onTimer() call a line above.

提交回复
热议问题