Using Countdown timer with async task - android

I am having trouble implementing async task with countdown timer class. I have a countdown timer that updates the ui;however, if I go to other applications the time starts from the beginning, so I need to use async task. Only problem is that I don't know how to incorporate async task with my countdown timer class, would anyone know how to solve this?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_count_down);
countDown = new CountDownTime(actualTimeFiniliazedInMilliSeconds, timeInterval);
countDown.start();
new UpdateCountDownTime().execute();
}
public class CountDownTime extends CountDownTimer {
/**
* #param millisInFuture The number of millis in the future from the call
* to {#link #start()} until the countdown is done and {#link #onFinish()}
* is called.
* #param countDownInterval The interval along the way to receive
* {#link #onTick(long)} callbacks.
*/
public CountDownTime(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
long millis = millisUntilFinished;
hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
// currentCountDownTime.setText(currentCountDownTime.getText() + String.valueOf(millisUntilFinished));
timeTextView.setText(hms);
}
#Override
public void onFinish() {
Intent goBack = new Intent(CountDownAct.this, ListOfAlarms.class);
startActivity(goBack);
finish();
}
}
#Override
protected void onPause() {
super.onPause();
timeTextView.setText(hms);
}
private class UpdateCountDownTime extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
countDown = new CountDownTime(actualTimeFiniliazedInMilliSeconds, timeInterval);
countDown.start();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
((TextView) findViewById(R.id.timeTextView)).setText(hms);
}
}

Create a instance of CountDownTime in the activity as a static field variable:
private static CountDownTime sCountDownTime = new CountDownTime(20000, 1000);
And start it in the activity anywhere you need:
sCountDownTime.start(this);
This is the modified CountDownTime class, make it static so it doesn't hold a strong reference of the outter activity. You may need to remove the activity.isFinishing\isDestroyed if you want to execute the code even if the activity that started this counter is finished\destroyed(etc. user pressed back key).
public static class CountDownTime extends CountDownTimer {
private WeakReference<Activity> mActivityRef;
private String mCurrentTime;
private boolean mStarted;
public CountDownTime(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
public void start(Activity activity) {
mActivityRef = new WeakReference<Activity>(activity);
if (!mStarted) {
mStarted = true;
start();
} else {
updateTextView();
}
}
#Override
public void onTick(long millisUntilFinished) {
long millis = millisUntilFinished;
mCurrentTime = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
updateTextView();
}
#Override
public void onFinish() {
Activity activity = mActivityRef.get();
if (activity != null && !activity.isFinishing() && !activity.isDestroyed()) {
activity.startActivity(new Intent(activity, SettingsActivity.class));
activity.finish();
}
mStarted = false;
}
private void updateTextView() {
Activity activity = mActivityRef.get();
if (activity != null && !activity.isFinishing() && !activity.isDestroyed()) {
TextView textView = (TextView) activity.findViewById(R.id.text_view);
textView.setText(mCurrentTime);
}
}
}

Try the following code. I took the count down of 3 min. I am saving the current time-stamp in onStop() in a preference, while in onResume() i am doing a small calculation to determine the time stapm from where the count down should start.
public class MainActivity extends Activity {
TextView textView;
private CountDownTime countDownTimer;
private PreferenceManager manager;
private String EXIT="exit",TIME_LAPSED="timeLapsed";
private long millisInFuture=3*60*1000;
private long countDownInterval=1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=(TextView)findViewById(R.id.textView1);
manager=new PreferenceManager();
}
#Override
protected void onResume() {
super.onResume();
if(manager.getLong(this, EXIT)<0){
countDownTimer=new CountDownTime(millisInFuture, 1000);
}else{
long time = manager.getLong(this,TIME_LAPSED)- (System.currentTimeMillis() - manager.getLong(this, EXIT));
countDownTimer=new CountDownTime(time, countDownInterval);
}
Log.e("ONRESUME ", "CALLED");
countDownTimer.start();
}
#Override
protected void onStop() {
manager.put(this, EXIT, System.currentTimeMillis());
manager.put(this, TIME_LAPSED, millisInFuture);
countDownTimer.cancel();
super.onStop();
Log.e("ONSTOP ", "CALLED");
}
public class PreferenceManager {
private static final String PREF_NAME = "app_pref";
public PreferenceManager() {};
private SharedPreferences getSharedPreferences(Context context) {
return context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
}
private Editor getPreferenceEditor(Context context) {
return getSharedPreferences(context).edit();
}
public long getLong(Context context, String key) {
return getSharedPreferences(context).getLong(key, -1);
}
public void put(Context context, String key, long value) {
Editor editor = getPreferenceEditor(context);
editor.putLong(key, value);
editor.commit();
}
}
public class CountDownTime extends CountDownTimer {
public CountDownTime(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
millisInFuture = millisInFuture - 1000;
long millis = millisUntilFinished;
textView.setText(String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))));
}
#Override
public void onFinish() {
/*Intent goBack = new Intent(CountDownAct.this, ListOfAlarms.class);
startActivity(goBack);
finish();*/
}
} }

Related

timer countdown 5,3,1 android

I have made a simple app about timer countdown. My code works perfectly, but the problem has come when I run this project.The first time my app counted normally, but the second time it counted 5,3,1 not 5,4,3,2,1
here's my code timer :
private Handler handler=new Handler();
public static int timer;
private OnTimeCompleteListener timeComplete=(OnTimeCompleteListener)this;
private Runnable timerThread=new Runnable() {
#Override
public void run() {
if(timer>0){
//Time is running
timer--;
timer_text.setText("Time : "+timer);
handler.postDelayed(this, 1000);
}else{
timeComplete.onTimeFinish();
}
}
};
public void startTimer(){
handler.postDelayed(timerThread, 100);
}
public void stopTimer(){
handler.removeCallbacks(timerThread);
}
how to make my timer work perfectly?
I thought about something like this:
private static final int TIMER_COUNTDOWN_VALUE = 5;
private Handler handler=new Handler();
private Runnable currentTimerRunnable = null;
public void startTimer() {
if( currentTimerRunnable == null ) {
currentTimerRunnable = new TimerRunnable( TIMER_COUNTDOWN_VALUE );
handler.postDelayed(currentTimerRunnable, 100);
}
}
public void stopTimer() {
if( currentTimerRunnable != null ) {
handler.removeCallbacks(currentTimerRunnable);
currentTimerRunnabel = null;
}
}
private class TimerRunnable implements Runnable {
private int timerValue;
private TimerRunnable(int startValue) {
timerValue = startValue;
#Override
public void run() {
if( timerValue > 0) {
timer--;
timerListener.onTimerUpdate( timerValue );
handler.postDelayed(this, 1000);
} else {
timerListener.onTimerFinished();
}
}
}
try this,
create CounterClass and call its start and cancle method where you want.
public class CounterClass extends CountDownTimer
{
public CounterClass(long millisInFuture, long countDownInterval)
{
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish()
{
//restart timer you wnat
//timer.start();
}
// #SuppressLint("NewApi");
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onTick(long millisUntilFinished)
{
long millis = millisUntilFinished;
String hms = String.format(
"%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
// System.out.println(hms);
tvTime.setText(hms);
}
}
create object of CounterClass and call it's method as discribe
timer = new CounterClass(26000, 1000);//for 26 second like,26,25....1,0.
timer.start()//where you need.
timer.cancle()//where you need.

Android CountDownTimer cancel the counting down

I have class MainActivity below, I need to cancel the counting down on method onBackPressed from other class. I also copied the CountDownTimer class below. How do I do it properly, any help? Thank you for reply.
#Override
public void onCreate(Bundle savedInstanceState) {
textViewTime = (TextView) findViewById(R.id.tv_Time);
textViewTime.setText(getString(R.string.countdown_time));
final CounterClass timer = new CounterClass(10999, 900);
timer.start();
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
timer.cancel();
}
});
}
#Override
public void onBackPressed() {
super.onBackPressed();
// here cancel //
}
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
textViewTime.setText("COMPLETED");
}
#Override
public void onTick(long millisUntilFinished) {
long millis = millisUntilFinished;
String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
textViewTime.setText(hms);
}
}
CountDownTimer has a cancel() method that can be called to terminate the timer.
Your MainActivity would look like this
public class MainActivity extends Activity {
private final CounterClass timer;
#Override
public void onCreate() {
timer = new CounterClass(10999, 900);
timer.start();
/* rest of the code omitted */
}
#Override
public void onBackPressed() {
super.onBackPressed();
timer.cancel()
}
}

how to get value from countdowntimer and display into toast

i have countdown timer from 1 to 9999 if i click start button the count will start, but if click stop button i need to get current value from countdown and display that value in toast but the countdown could not stop if i click stop button please help me
private CountDownTimer countDownTimer;
private boolean timerHasStarted = false;
private Button startB;
public TextView ;
private final long startTime = 9999 * 1;
private final long interval = 1 *1 ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startB = (Button) this.findViewById(R.id.button);
startB.setOnClickListener(this);
text = (TextView) this.findViewById(R.id.timer);
countDownTimer = new MyCountDownTimer(startTime, interval);
text.setText(text.getText() + String.valueOf(startTime / 1));
}
public void onClick(View v) {
if (!timerHasStarted) {
countDownTimer.start();
timerHasStarted = true;
startB.setText("STOP");
} else {
/*countDownTimer.cancel();
timerHasStarted = false;
startB.setText("RESTART");*/
}
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
//text.setText("Time's up!");
countDownTimer.start();
}
#Override
public void onTick(long millisUntilFinished) {
text.setText("" + millisUntilFinished / 1);
}
}
thank you
Here is my countdown timer:
QuestionCountdownTimer
public class QuestionCountdownTimer extends CountDownTimer {
private TextView remainingTimeDisplay;
private Context context;
public QuestionCountdownTimer(Context context,long millisInFuture, long countDownInterval,TextView remainingTimeDisplay) {
super(millisInFuture, countDownInterval);
this.context = context;
this.remainingTimeDisplay = remainingTimeDisplay;
}
#Override
public void onTick(long millisUntilFinished) {
long millis = millisUntilFinished;
String hms = String.format("%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
remainingTimeDisplay.setText(hms);
}
#Override
public void onFinish() {
Toast.makeText(context,"COUNTDOWN FINISH :)",Toast.LENGTH_SHORT).show();
}
}
Note:
TextView remainingTimeDisplay
remainingTimeDisplay.setText(hms);
I use it to display the remaining time using a TextView
Here I call the timer:
//Start Quiz timer
QuestionCountdownTimer timer = new QuestionCountdownTimer(this,10000, 1000, remainingTimeDisplay);
timer.start();
-first parameter: this - I use it for context to show Toast message
-second parameter: 10000 - total time (10 sec)
-third parameter: 1000 - countdown interval (1 sec)
-last parameter: dispaly remaining time in real time
Tested and working
Create your CountDownTimer like this:
public class MyCountDownTimer extends CountDownTimer
{
private long timePassed = 0;
public MyCountDownTimer(long startTime, long interval)
{
super(startTime, interval);
}
#Override
public void onFinish()
{
//text.setText("Time's up!");
countDownTimer.start();
}
#Override
public void onTick(long millisUntilFinished)
{
timePassed++;
text.setText("" + millisUntilFinished / 1);
}
public long getTimePassed()
{
return timePassed;
}
}
And on your onClick just do:
((MyCoundDownTimer) countDownTimer).getTimePassed();
to retrieve the time and set your textview text to it.
You should use handler
private Handler tickResponseHandler = new Handler() {
public void handleMessage(Message msg) {
int time = msg.what;
//make toast or do what you want
}
}
and pass it to MyCountDownTimer constructor
private Handler handler;
public MyCountDownTimer(long startTime, long interval, Handler handler) {
super(startTime, interval);
this.handler = handler;
}
And send message
#Override
public void onTick(long millisUntilFinished) {
text.setText("" + millisUntilFinished / 1);
Message msg = new Message();
msg.what = millisUntilFinished/1;
handler.sendMessage(msg);
}
That's all you need to do :)

How to add and remove time on CountDownTimer?

The question is: How can I add or remove time from the CountDownTimer during the count down?
For example: The user does something good: +5sec, the user does something wrong: -5sec.
Can someone help me with some code?
Maybe something like this
abstract class MyTimer {
public MyTimer(long deadline, long interval)
{
mDeadline = deadline;
mInterval = interval;
mTimer = new MyCountDownTimer(mDeadline, mInterval);
}
public synchronized void start() {
mTimer.start();
}
public abstract void onTick(long time);
public abstract void onFinish();
public synchronized void userDidRight()
{
mTimer.cancel();
mTimer = new MyCountDownTimer(mDeadline, mInterval += 5000);
mTimer.start();
}
public synchronized void userDidWrong()
{
mTimer.cancel();
mTimer = new MyCountDownTimer(mDeadline, mInterfval -= 5000);
mTimer.start();
}
private class MyCountDownTimer extends CountDownTimer() {
private abstract void onFinish() {
MyTimer.this.onFinish();
}
private abstract void onTick(long time) {
MyTimer.this.onTick(time);
}
}
private MyCountDownTimer mTimer;
}
You could restart the timer every time the user changes:
class Timer {
private long remainingTime;
private CoundDownTimer timer;
public void addTime(long addedTimeInMillis) {
createNewTimer(remainingTime + addedTimeInMills);
}
public void createNewTimer(long timeInMillis) {
if(timer != null) {
timer.cancel();
}
timer = new CountDownTimer(timeInMillis, 1000) {
#Override
public void onTick(final long millisUntilFinished) {
remainingTime = millisUntilFinished;
}
#Override
public void onFinish() {
// do something here
}
}.start();
}
}
private class startTimer extends CountDownTimer
{
public startTimer(long millisInFuture, long countDownInterval)
{
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
currenttime=millisUntilFinished;
textview.setText("" + currenttime / 1000);
}
#Override
public void onFinish() {
textview.setText("done");
}
}
The above class is a simple derived class of CountDownTimer
CountDownTimer timer = new CountDownTimer(30000,1000);
timer.start();
long currentTime;
For example the above timer starts from 30 secs,decreases by one for each second.
To increase or decrease the timer dynamically you can cancel the old timer and initialize with your new time as shown below
timer.cancel();
timer = new CountDownTimer(currentTime+5000,1000);// +5000 to increase by 5 secs
timer.start();
you can make timer,currentTime variables as global then you can use the two different parts of code at different location.

Pause CountDownTimer in Android when activity is not in front

I have an activity that uses a CountDownTimer that counts down from 10. How do I pause that timer when the activity is no longer in focus, like if the user get a call or something, then resume the timer when the user goes back to the activity? Is this even possible?
I would add something to the onTick handler to save the progress of the timer in your class (number of milliseconds left).
In the onPause() method for the activity call cancel() on the timer.
In the onResume() method for the activity create a new timer with the saved number of milliseconds left.
You can use pause() to pause the timer and later on Start or Resume the countDownTimer by calling start().
/**
* This class uses the native CountDownTimer to
* create a timer which could be paused and then
* started again from the previous point. You can
* provide implementation for onTick() and onFinish()
* then use it in your projects.
*/
public abstract class CountDownTimerPausable {
long millisInFuture = 0;
long countDownInterval = 0;
long millisRemaining = 0;
CountDownTimer countDownTimer = null;
boolean isPaused = true;
public CountDownTimerPausable(long millisInFuture, long countDownInterval) {
super();
this.millisInFuture = millisInFuture;
this.countDownInterval = countDownInterval;
this.millisRemaining = this.millisInFuture;
}
private void createCountDownTimer(){
countDownTimer = new CountDownTimer(millisRemaining,countDownInterval) {
#Override
public void onTick(long millisUntilFinished) {
millisRemaining = millisUntilFinished;
CountDownTimerPausable.this.onTick(millisUntilFinished);
}
#Override
public void onFinish() {
CountDownTimerPausable.this.onFinish();
}
};
}
/**
* Callback fired on regular interval.
*
* #param millisUntilFinished The amount of time until finished.
*/
public abstract void onTick(long millisUntilFinished);
/**
* Callback fired when the time is up.
*/
public abstract void onFinish();
/**
* Cancel the countdown.
*/
public final void cancel(){
if(countDownTimer!=null){
countDownTimer.cancel();
}
this.millisRemaining = 0;
}
/**
* Start or Resume the countdown.
* #return CountDownTimerPausable current instance
*/
public synchronized final CountDownTimerPausable start(){
if(isPaused){
createCountDownTimer();
countDownTimer.start();
isPaused = false;
}
return this;
}
/**
* Pauses the CountDownTimerPausable, so it could be resumed(start)
* later from the same point where it was paused.
*/
public void pause()throws IllegalStateException{
if(isPaused==false){
countDownTimer.cancel();
} else{
throw new IllegalStateException("CountDownTimerPausable is already in pause state, start counter before pausing it.");
}
isPaused = true;
}
public boolean isPaused() {
return isPaused;
}
}
No need to create a new Timer, just set the millisUntilFinished = total. For instance
private CountDownTimer cdTimer;
private long total = 30000;
...
toggleButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
if(toggleButton.isChecked()) {
startCountDownTimer();
}else{
cdTimer.cancel();
}
}
});
...
private void startCountDownTimer() {
cdTimer = new CountDownTimer(total, 1000) {
public void onTick(long millisUntilFinished) {
//update total with the remaining time left
total = millisUntilFinished;
nTimeLabel.setText("seconds remaining: " + millisUntilFinished/ 1000);
}
public void onFinish() {
nTimeLabel.setText("done!");
}
}.start();
}
This must be exactly what you're looking for. Source is this Gist.
package alt.android.os;
import android.os.Handler;
import android.os.SystemClock;
import android.os.Message;
public abstract class CountDownTimer {
/**
* Millis since epoch when alarm should stop.
*/
private final long mMillisInFuture;
/**
* The interval in millis that the user receives callbacks
*/
private final long mCountdownInterval;
private long mStopTimeInFuture;
private long mPauseTime;
private boolean mCancelled = false;
private boolean mPaused = false;
/**
* #param millisInFuture The number of millis in the future from the call
* to {#link #start()} until the countdown is done and {#link #onFinish()}
* is called.
* #param countDownInterval The interval along the way to receive
* {#link #onTick(long)} callbacks.
*/
public CountDownTimer(long millisInFuture, long countDownInterval) {
mMillisInFuture = millisInFuture;
mCountdownInterval = countDownInterval;
}
/**
* Cancel the countdown.
*
* Do not call it from inside CountDownTimer threads
*/
public final void cancel() {
mHandler.removeMessages(MSG);
mCancelled = true;
}
/**
* Start the countdown.
*/
public synchronized final CountDownTimer start() {
if (mMillisInFuture <= 0) {
onFinish();
return this;
}
mStopTimeInFuture = SystemClock.elapsedRealtime() + mMillisInFuture;
mHandler.sendMessage(mHandler.obtainMessage(MSG));
mCancelled = false;
mPaused = false;
return this;
}
/**
* Pause the countdown.
*/
public long pause() {
mPauseTime = mStopTimeInFuture - SystemClock.elapsedRealtime();
mPaused = true;
return mPauseTime;
}
/**
* Resume the countdown.
*/
public long resume() {
mStopTimeInFuture = mPauseTime + SystemClock.elapsedRealtime();
mPaused = false;
mHandler.sendMessage(mHandler.obtainMessage(MSG));
return mPauseTime;
}
/**
* Callback fired on regular interval.
* #param millisUntilFinished The amount of time until finished.
*/
public abstract void onTick(long millisUntilFinished);
/**
* Callback fired when the time is up.
*/
public abstract void onFinish();
private static final int MSG = 1;
// handles counting down
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
synchronized (CountDownTimer.this) {
if (!mPaused) {
final long millisLeft = mStopTimeInFuture - SystemClock.elapsedRealtime();
if (millisLeft <= 0) {
onFinish();
} else if (millisLeft < mCountdownInterval) {
// no tick, just delay until done
sendMessageDelayed(obtainMessage(MSG), millisLeft);
} else {
long lastTickStart = SystemClock.elapsedRealtime();
onTick(millisLeft);
// take into account user's onTick taking time to execute
long delay = lastTickStart + mCountdownInterval - SystemClock.elapsedRealtime();
// special case: user's onTick took more than interval to
// complete, skip to next interval
while (delay < 0) delay += mCountdownInterval;
if (!mCancelled) {
sendMessageDelayed(obtainMessage(MSG), delay);
}
}
}
}
}
};
}
You can try using Hourglass
Hourglass hourglass = new Hourglass(50000, 1000) {
#Override
public void onTimerTick(long timeRemaining) {
// Update UI
Toast.show(MainActivity.this, String.valueOf(timeRemaining), Toast.LENGTH_SHORT).show();
}
#Override
public void onTimerFinish() {
// Timer finished
Toast.show(MainActivity.this, "Timer finished", Toast.LENGTH_SHORT).show();
}
};
Use hourglass.startTimer(); to start the timer.
It has helper methods which allow to pause and resume the timer.
hourglass.pauseTimer();
AND
hourglass.resumeTimer();
Here is the code below .Use it in your activities it works fine.
public class MainActivity extends AppCompatActivity {
TextView textview;
final static long INTERVAL = 1000;
final static long TIMEOUT = 11000;
static long millisecondsleft;
boolean isPause =false;
CountDownTimer countDownTimer;
CountDownTimer countDownTimeronResume;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview=findViewById(R.id.textviewcheck);
}
#Override
protected void onResume() {
super.onResume();
if(isPause == false) {
countDownTimer = new CountDownTimer(TIMEOUT, INTERVAL) {
#Override
public void onTick(long millisUntilFinished) {
millisecondsleft = millisUntilFinished;
textview.setText(":" + String.format("%02d", millisUntilFinished / 1000));
}
#Override
public void onFinish() {
textview.setText("DONE!");
}
}.start();
} else{
countDownTimeronResume = new CountDownTimer(millisecondsleft, INTERVAL) {
#Override
public void onTick(long millisUntilFinished) {
Toast.makeText(MainActivity.this, "ONPAUSED", Toast.LENGTH_SHORT).show();
millisecondsleft = millisUntilFinished;
textview.setText(":" + String.format("%02d", millisUntilFinished / 1000));
}
#Override
public void onFinish() {
textview.setText("DONE!");
}
}.start();
}
}
#Override
protected void onPause() {
super.onPause();
if(countDownTimer!=null){
countDownTimer.cancel();
isPause = true;
}
if(countDownTimeronResume!=null){
countDownTimeronResume.cancel();
}
}
}
For Kotlin user, checkout this
For eg:
// Init timer
lateinit var timerExt: CountDownTimerExt
timerExt = object : CountDownTimerExt(TIMER_DURATION, TIMER_INTERVAL) {
override fun onTimerTick(millisUntilFinished: Long) {
Log.d("MainActivity", "onTimerTick $millisUntilFinished")
}
override fun onTimerFinish() {
Log.d("MainActivity", "onTimerFinish")
}
}
// Start/Resume timer
timerExt.start()
// Pause timer
timerExt.pause()
// Restart timer
timerExt.restart()

Categories

Resources