Created
September 23, 2020 09:06
-
-
Save Taosif7/e61f4296e1e394fe52b33e6d1fc56fa5 to your computer and use it in GitHub Desktop.
A Timer That runs infinitely and calls its listeners on definite intervals
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.os.CountDownTimer; | |
import java.util.Arrays; | |
public class InfiniteCounter extends CountDownTimer { | |
private static final int MAX_LISTENERS = 100; | |
private static InfiniteCounter timer; | |
private static InfiniteCounterListener[] listenerList = new InfiniteCounterListener[MAX_LISTENERS]; | |
private InfiniteCounter(long millisInFuture, long countDownInterval) { | |
super(millisInFuture, countDownInterval); | |
} | |
//Milliseconds Intervals in which the counter should call its listeners | |
public static InfiniteCounter initInstance(int intervalMillis) { | |
removeAllListeners(); | |
if (timer == null) { | |
timer = new InfiniteCounter(60 * 60 * 1000, intervalMillis); | |
timer.start(); | |
} | |
return timer; | |
} | |
public static void attachListener(InfiniteCounterListener listener) { | |
for (int i = 0; i < MAX_LISTENERS; i++) { | |
if (listenerList[i] == null) { | |
listenerList[i] = listener; | |
break; | |
} | |
} | |
} | |
public static void removeListener(InfiniteCounterListener listener) { | |
for (int i = 0; i < MAX_LISTENERS; i++) { | |
if (listenerList[i] == listener) { | |
listenerList[i] = null; | |
break; | |
} | |
} | |
} | |
private static void removeAllListeners() { | |
Arrays.fill(listenerList, null); | |
} | |
public static void stopTimer() { | |
removeAllListeners(); | |
if (timer != null) timer.cancel(); | |
timer = null; | |
} | |
@Override | |
public void onTick(long l) { | |
for (int i = 0; i < MAX_LISTENERS; i++) { | |
if (listenerList[i] != null) listenerList[i].onTick(); | |
} | |
} | |
@Override | |
public void onFinish() { | |
timer.start(); | |
} | |
public interface InfiniteCounterListener { | |
void onTick(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment