Android timer stuff
Posted By Thaylin on December 6, 2011
Wow, it’s been a while since I’ve last posted!
Just wanted to toss up some code for creating a timer in android. One would think you would just utilize the java.utils.Timer class but that creates a new thread and can create issues with your application. Plus it’s a pain to access stuff from the timer. Android has an alternative to keep everything all together and it’s quite easy to implement.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | private Handler timerHandler; private int timerTime = 5000; //in milliseconds private void createTimer() { timerHandler = new Handler(); } private void startTimer() { //resets timer and posts the delayed call rotationHandler.removeCallbacks(mUpdateTimeTask); rotationHandler.postDelayed(mUpdateTimeTask, timerTime); } private void stopTimer() { rotationHandler.removeCallbacks(mUpdateTimeTask); } private Runnable mUpdateTimeTask = new Runnable() { public void run() { //do your thing //repeat timer if you need to rotationHandler.postDelayed(this, timerTime); } }; |
Comments
Leave a Reply
Please note: Comment moderation is currently enabled so there will be a delay between when you post your comment and when it shows up. Patience is a virtue; there is no need to re-submit your comment.