project_files/Android-build/SDL-android-project/src/org/hedgewars/hedgeroid/netplay/TickHandler.java
changeset 7508 763d3961400b
parent 7504 ed1d52c5aa94
child 7550 3c4b4cb40f40
equal deleted inserted replaced
7504:ed1d52c5aa94 7508:763d3961400b
     1 package org.hedgewars.hedgeroid.netplay;
       
     2 
       
     3 import android.os.Handler;
       
     4 import android.os.Looper;
       
     5 import android.os.Message;
       
     6 
       
     7 /**
       
     8  * This class handles regularly calling a specified runnable
       
     9  * on the looper provided in the constructor. The first call
       
    10  * occurs without delay (though still via the looper), all
       
    11  * following calls are delayed by (approximately) the interval.
       
    12  * The interval can be changed at any time, which will cause
       
    13  * an immediate execution of the runnable again.
       
    14  */
       
    15 public class TickHandler extends Handler {
       
    16 	private final Runnable callback;
       
    17 	private int messageId;
       
    18 	private long interval;
       
    19 	private boolean running;
       
    20 	
       
    21 	public TickHandler(Looper looper, long interval, Runnable callback) {
       
    22 		super(looper);
       
    23 		this.callback = callback;
       
    24 		this.interval = interval;
       
    25 	}
       
    26 	
       
    27 	public synchronized void stop() {
       
    28 		messageId++;
       
    29 		running = false;
       
    30 	}
       
    31 	
       
    32 	public synchronized void start() {
       
    33 		messageId++;
       
    34 		sendMessage(obtainMessage(messageId));
       
    35 		running = true;
       
    36 	}
       
    37 	
       
    38 	public synchronized void setInterval(long interval) {
       
    39 		this.interval = interval;
       
    40 		if(running) {
       
    41 			start();
       
    42 		}
       
    43 	}
       
    44 	
       
    45 	@Override
       
    46 	public synchronized void handleMessage(Message msg) {
       
    47 		if(msg.what == messageId) {
       
    48 			callback.run();
       
    49 		}
       
    50 		if(msg.what == messageId) {
       
    51 			sendMessageDelayed(obtainMessage(messageId), interval);
       
    52 		}
       
    53 	}
       
    54 }