Search code examples
javaandroidtimer

Android: how to use a timer


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 ImageView, have that ImageView swap images for a second, then return to the original image. ( this is for a tapping game )

sounds easy enough, right? I've spent the whole day trying to get a standard Java Timer / TimerTask to work.. no luck..

is there a better way? I mean, is there an Android specific way to do something like this? If not, then what is the ideal way?

thanks for all your help in advance guys! -g


Solution

  • 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<SystemTimerListener> clockListener = new ArrayList<SystemTimerListener>();
    
        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);        
        }
    }