How to set a timer in android

前端 未结 13 1730
天命终不由人
天命终不由人 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:09

    I'm an Android newbie but here is the timer class I created based on the answers above. It works for my app but I welcome any suggestions.

    Usage example:

    ...{
    public Handler uiHandler = new Handler();
    
      private Runnable runMethod = new Runnable()
        {
            public void run()
            {
                  // do something
            }
        };
    
        timer = new UITimer(handler, runMethod, timeoutSeconds*1000);       
            timer.start();
    }...
    
    public class UITimer
    {
        private Handler handler;
        private Runnable runMethod;
        private int intervalMs;
        private boolean enabled = false;
        private boolean oneTime = false;
    
        public UITimer(Handler handler, Runnable runMethod, int intervalMs)
        {
            this.handler = handler;
            this.runMethod = runMethod;
            this.intervalMs = intervalMs;
        }
    
        public UITimer(Handler handler, Runnable runMethod, int intervalMs, boolean oneTime)
        {
            this(handler, runMethod, intervalMs);
            this.oneTime = oneTime;
        }
    
        public void start()
        {
            if (enabled)
                return;
    
            if (intervalMs < 1)
            {
                Log.e("timer start", "Invalid interval:" + intervalMs);
                return;
            }
    
            enabled = true;
            handler.postDelayed(timer_tick, intervalMs);        
        }
    
        public void stop()
        {
            if (!enabled)
                return;
    
            enabled = false;
            handler.removeCallbacks(runMethod);
            handler.removeCallbacks(timer_tick);
        }
    
        public boolean isEnabled()
        {
            return enabled;
        }
    
        private Runnable timer_tick = new Runnable()
        {
            public void run()
            {
                if (!enabled)
                    return;
    
                handler.post(runMethod);
    
                if (oneTime)
                {
                    enabled = false;
                    return;
                }
    
                handler.postDelayed(timer_tick, intervalMs);
            }
        }; 
    }
    

提交回复
热议问题