Android: how to use a timer

前端 未结 2 1657
南旧
南旧 2021-01-06 12:19

this is my first post..

so I\'m learning Android & Java (coming from Actionscript), and I\'m working on a project where :

I\'m trying to click an Image

2条回答
  •  佛祖请我去吃肉
    2021-01-06 13:08

    Here is my Android timer class which should work fine. It sends a signal every second. Change schedule() call is you want a different scheme.

    Note that you cannot change Android gui stuff in the timer thread, this is only allowed in the main thread. This is why you have to use a Handler to give the control back to the main thread.

    import java.util.ArrayList;
    import java.util.List;
    import java.util.Timer;
    import java.util.TimerTask;
    
    import android.os.Handler;
    import android.os.Message;
    
    public class SystemTimerAndroid {
        private final Timer clockTimer;
    
        private class Task extends TimerTask {
            public void run() {
                timerHandler.sendEmptyMessage(0);
            }
        }
    
        private final Handler timerHandler = new Handler() {
            public void handleMessage (Message  msg) {
                // runs in context of the main thread
                timerSignal();
            }
        };
    
        private List clockListener = new ArrayList();
    
        public SystemTimerAndroid() {
            clockTimer = new Timer();
            clockTimer.schedule(new Task(), 1000, 1000);
        }
    
        private void timerSignal() {
            for(SystemTimerListener listener : clockListener)
                listener.onSystemTimeSignal();      
        }
    
        public void killTimer() {
            clockTimer.cancel();
        }
    
        @Override
        public void addListener(SystemTimerListener listener) {
            clockListener.add(listener);        
        }
    }
    

提交回复
热议问题