project_files/Android-build/SDL-android-project/src/org/hedgewars/hedgeroid/netplay/TickHandler.java
author Medo <smaxein@googlemail.com>
Sun, 12 Aug 2012 22:37:57 +0200
changeset 7482 d70a5b0d1190
parent 7476 2fb781bbdd51
permissions -rw-r--r--
frontlib improvements: - Added README with overview documentation - Improved code documentation/comments - Added flib_gameconn_send_quit to gracefully exit a running game - Changed the type of some size variables to size_t - Fixed starting a mission/training sending the mission script like a multiplayer script - Removed reference counters from flib_scheme and flib_map - Removed INGAME state from netconn (there is no useful difference to ROOM state) - Added extras/jnacontrol.c to warn when functions signatures used by Hedgeroid change - Other small code improvements

package org.hedgewars.hedgeroid.netplay;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

/**
 * This class handles regularly calling a specified runnable
 * on the looper provided in the constructor. The first call
 * occurs without delay (though still via the looper), all
 * following calls are delayed by (approximately) the interval.
 * The interval can be changed at any time, which will cause
 * an immediate execution of the runnable again.
 */
public class TickHandler extends Handler {
	private final Runnable callback;
	private int messageId;
	private long interval;
	private boolean running;
	
	public TickHandler(Looper looper, long interval, Runnable callback) {
		super(looper);
		this.callback = callback;
		this.interval = interval;
	}
	
	public synchronized void stop() {
		messageId++;
		running = false;
	}
	
	public synchronized void start() {
		messageId++;
		sendMessage(obtainMessage(messageId));
		running = true;
	}
	
	public synchronized void setInterval(long interval) {
		this.interval = interval;
		if(running) {
			start();
		}
	}
	
	@Override
	public synchronized void handleMessage(Message msg) {
		if(msg.what == messageId) {
			callback.run();
		}
		if(msg.what == messageId) {
			sendMessageDelayed(obtainMessage(messageId), interval);
		}
	}
}