Created
June 12, 2020 08:58
-
-
Save harish81/80d2817e3b3a1c6851a8a024e83a9cbd to your computer and use it in GitHub Desktop.
Easy Repeat Task Timer For Android With listener support.
This file contains hidden or 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
RepeatTaskTimer timer = new RepeatTaskTimer(this, new RepeatTaskTimer.Listener() { | |
@Override | |
public void onTick(long remainMillis) { | |
long minute = remainMillis / 60000; | |
long second = (remainMillis % 60000) / 1000; | |
btnResend.setText("Resend in " + minute + ":" + second); | |
} | |
@Override | |
public void onFinish() { | |
isExpired = true; | |
btnResend.setText("OTP Expired!"); | |
btnVerify.setText("Resend OTP"); | |
} | |
}, 2 * 60 * 1000, 1000); | |
timer.start(); |
This file contains hidden or 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.app.Activity; | |
import java.util.Timer; | |
import java.util.TimerTask; | |
public class RepeatTaskTimer extends TimerTask { | |
private long timeInMillis; | |
private long delay; | |
private long finishTime; | |
private Listener listener; | |
private Activity activity; | |
private Timer timer = new Timer(); | |
public RepeatTaskTimer(Activity activity, Listener listener, long finishTime, long delay) { | |
this.listener = listener; | |
this.activity = activity; | |
this.timeInMillis = 0; | |
this.delay = delay; | |
this.finishTime = finishTime; | |
} | |
public RepeatTaskTimer(Activity activity, Listener listener, long finishTime) { | |
this(activity, listener, finishTime, 1000); | |
} | |
public void start() { | |
timer.scheduleAtFixedRate(this, 0, delay); | |
} | |
@Override | |
public void run() { | |
activity.runOnUiThread(new Runnable() { | |
@Override | |
public void run() { | |
timeInMillis += delay; | |
if (timeInMillis >= finishTime) { | |
listener.onFinish(); | |
cancel(); | |
} else | |
listener.onTick(finishTime - timeInMillis); | |
} | |
}); | |
} | |
public static interface Listener { | |
void onTick(long remainMillis); | |
void onFinish(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment