| 1 | |
package com.timjohnstondev.timer; |
| 2 | |
|
| 3 | |
public class CountDownTimer |
| 4 | |
{ |
| 5 | |
public static final int COUNTER_DEFAULT = 30 * 60; |
| 6 | |
private boolean isRunning; |
| 7 | |
private long remainingTime; |
| 8 | |
private long lastUpdate; |
| 9 | |
|
| 10 | |
public CountDownTimer() |
| 11 | |
{ |
| 12 | 20 | this(COUNTER_DEFAULT); |
| 13 | 20 | } |
| 14 | |
|
| 15 | |
public CountDownTimer(final int initialValue) |
| 16 | 21 | { |
| 17 | 21 | initialize(initialValue); |
| 18 | 21 | } |
| 19 | |
|
| 20 | |
public final void initialize(final int initialValue) |
| 21 | |
{ |
| 22 | 26 | remainingTime = initialValue * 1000; |
| 23 | 26 | } |
| 24 | |
|
| 25 | |
public final void start() |
| 26 | |
{ |
| 27 | 2 | lastUpdate = System.currentTimeMillis(); |
| 28 | 2 | isRunning = true; |
| 29 | 2 | } |
| 30 | |
|
| 31 | |
public final void stop() |
| 32 | |
{ |
| 33 | 2 | lastUpdate = System.currentTimeMillis(); |
| 34 | 2 | isRunning = false; |
| 35 | 2 | } |
| 36 | |
|
| 37 | |
public final int getRemainingSeconds() |
| 38 | |
{ |
| 39 | 8 | if (isRunning) |
| 40 | |
{ |
| 41 | 1 | final long now = System.currentTimeMillis(); |
| 42 | 1 | remainingTime -= now - lastUpdate; |
| 43 | 1 | lastUpdate = now; |
| 44 | |
|
| 45 | 1 | if (remainingTime <= 500) |
| 46 | |
{ |
| 47 | 1 | remainingTime = 0; |
| 48 | 1 | stop(); |
| 49 | |
} |
| 50 | |
} |
| 51 | 8 | return (int) ((remainingTime + 500) / 1000); |
| 52 | |
} |
| 53 | |
|
| 54 | |
public final boolean isRunning() |
| 55 | |
{ |
| 56 | 4 | return isRunning; |
| 57 | |
} |
| 58 | |
} |