How to set timer in android?

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

    0 讨论(0)
  • 2020-11-22 01:37

    If anyone is interested, I started playing around with creating a standard object to run on an activities UI thread. Seems to work ok. Comments welcome. I'd love this to be available on the layout designer as a component to drag onto an Activity. Can't believe something like that doesn't already exist.

    package com.example.util.timer;
    
    import java.util.Timer;
    import java.util.TimerTask;
    
    import android.app.Activity;
    
    public class ActivityTimer {
    
        private Activity m_Activity;
        private boolean m_Enabled;
        private Timer m_Timer;
        private long m_Delay;
        private long m_Period;
        private ActivityTimerListener m_Listener;
        private ActivityTimer _self;
        private boolean m_FireOnce;
    
        public ActivityTimer() {
            m_Delay = 0;
            m_Period = 100;
            m_Listener = null;
            m_FireOnce = false;
            _self = this;
        }
    
        public boolean isEnabled() {
            return m_Enabled;
        }
    
        public void setEnabled(boolean enabled) {
            if (m_Enabled == enabled)
                return;
    
            // Disable any existing timer before we enable a new one
            Disable();
    
            if (enabled) {
                Enable();
            }
        }
    
        private void Enable() {
            if (m_Enabled)
                return;
    
            m_Enabled = true;
    
            m_Timer = new Timer();
            if (m_FireOnce) {
                m_Timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        OnTick();
                    }
                }, m_Delay);
            } else {
                m_Timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        OnTick();
                    }
                }, m_Delay, m_Period);
            }
        }
    
        private void Disable() {
            if (!m_Enabled)
                return;
    
            m_Enabled = false;
    
            if (m_Timer == null)
                return;
    
            m_Timer.cancel();
            m_Timer.purge();
            m_Timer = null;
        }
    
        private void OnTick() {
            if (m_Activity != null && m_Listener != null) {
                m_Activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        m_Listener.OnTimerTick(m_Activity, _self);
                    }
                });
            }
            if (m_FireOnce)
                Disable();
        }
    
        public long getDelay() {
            return m_Delay;
        }
    
        public void setDelay(long delay) {
            m_Delay = delay;
        }
    
        public long getPeriod() {
            return m_Period;
        }
    
        public void setPeriod(long period) {
            if (m_Period == period)
                return;
            m_Period = period;
        }
    
        public Activity getActivity() {
            return m_Activity;
        }
    
        public void setActivity(Activity activity) {
            if (m_Activity == activity)
                return;
            m_Activity = activity;
        }
    
        public ActivityTimerListener getActionListener() {
            return m_Listener;
        }
    
        public void setActionListener(ActivityTimerListener listener) {
            m_Listener = listener;
        }
    
        public void start() {
            if (m_Enabled)
                return;
            Enable();
        }
    
        public boolean isFireOnlyOnce() {
            return m_FireOnce;
        }
    
        public void setFireOnlyOnce(boolean fireOnce) {
            m_FireOnce = fireOnce;
        }
    }
    

    In the activity, I have this onStart:

    @Override
    protected void onStart() {
        super.onStart();
    
        m_Timer = new ActivityTimer();
        m_Timer.setFireOnlyOnce(true);
        m_Timer.setActivity(this);
        m_Timer.setActionListener(this);
        m_Timer.setDelay(3000);
        m_Timer.start();
    }
    
    0 讨论(0)
  • 2020-11-22 01:39

    This is some simple code for a timer:

    Timer timer = new Timer();
    TimerTask t = new TimerTask() {       
        @Override
        public void run() {
    
            System.out.println("1");
        }
    };
    timer.scheduleAtFixedRate(t,1000,1000);
    
    0 讨论(0)
  • 2020-11-22 01:43

    I use this way:

    String[] array={
           "man","for","think"
    }; int j;
    

    then below the onCreate

    TextView t = findViewById(R.id.textView);
    
        new CountDownTimer(5000,1000) {
    
            @Override
            public void onTick(long millisUntilFinished) {}
    
            @Override
            public void onFinish() {
                t.setText("I "+array[j] +" You");
                j++;
                if(j== array.length-1) j=0;
                start();
            }
        }.start();
    

    it's easy way to solve this problem.

    0 讨论(0)
  • 2020-11-22 01:45

    If one just want to schedule a countdown until a time in the future with regular notifications on intervals along the way, you can use the CountDownTimer class that is available since API level 1.

    new CountDownTimer(30000, 1000) {
        public void onTick(long millisUntilFinished) {
            editText.setText("Seconds remaining: " + millisUntilFinished / 1000);
        }
    
        public void onFinish() {
            editText.setText("Done");
        }
    }.start();
    
    0 讨论(0)
  • 2020-11-22 01:45

    Here is a simple reliable way...

    Put the following code in your Activity, and the tick() method will be called every second in the UI thread while your activity is in the "resumed" state. Of course, you can change the tick() method to do what you want, or to be called more or less frequently.

    @Override
    public void onPause() {
        _handler = null;
        super.onPause();
    }
    
    private Handler _handler;
    
    @Override
    public void onResume() {
        super.onResume();
        _handler = new Handler();
        Runnable r = new Runnable() {
            public void run() {
                if (_handler == _h0) {
                    tick();
                    _handler.postDelayed(this, 1000);
                }
            }
    
            private final Handler _h0 = _handler;
        };
        r.run();
    }
    
    private void tick() {
        System.out.println("Tick " + System.currentTimeMillis());
    }
    

    For those interested, the "_h0=_handler" code is necessary to avoid two timers running simultaneously if your activity is paused and resumed within the tick period.

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