1 /* 2 * Hedgewars for Android. An Android port of Hedgewars, a free turn based strategy game 3 * Copyright (C) 2012 Simeon Maxein <smaxein@googlemail.com> 4 * 5 * This program is free software; you can redistribute it and/or 6 * modify it under the terms of the GNU General Public License 7 * as published by the Free Software Foundation; either version 2 8 * of the License, or (at your option) any later version. 9 * 10 * This program is distributed in the hope that it will be useful, 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 * GNU General Public License for more details. 14 * 15 * You should have received a copy of the GNU General Public License 16 * along with this program; if not, write to the Free Software 17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 18 */ 19 20 package org.hedgewars.hedgeroid.util; 21 22 import android.os.Handler; 23 import android.os.Looper; 24 import android.os.Message; 25 26 /** 27 * This class handles regularly calling a specified runnable 28 * on the looper provided in the constructor. The first call 29 * occurs without delay (though still via the looper), all 30 * following calls are delayed by (approximately) the interval. 31 * The interval can be changed at any time, which will cause 32 * an immediate execution of the runnable again. 33 */ 34 public class TickHandler extends Handler { 35 private final Runnable callback; 36 private int messageId; 37 private long interval; 38 private boolean running; 39 TickHandler(Looper looper, long interval, Runnable callback)40 public TickHandler(Looper looper, long interval, Runnable callback) { 41 super(looper); 42 this.callback = callback; 43 this.interval = interval; 44 } 45 stop()46 public synchronized void stop() { 47 messageId++; 48 running = false; 49 } 50 start()51 public synchronized void start() { 52 messageId++; 53 sendMessage(obtainMessage(messageId)); 54 running = true; 55 } 56 setInterval(long interval)57 public synchronized void setInterval(long interval) { 58 this.interval = interval; 59 if(running) { 60 start(); 61 } 62 } 63 64 @Override handleMessage(Message msg)65 public synchronized void handleMessage(Message msg) { 66 if(msg.what == messageId) { 67 callback.run(); 68 } 69 if(msg.what == messageId) { 70 sendMessageDelayed(obtainMessage(messageId), interval); 71 } 72 } 73 }