Reputation: 655
I am trying to show a countdown timer onPreExecute and End the timer onPostExecute.I have below code which is working fine onPreExecute but I am not finding any way how to dismiss this timer on onPostExecute.Below is my timer code
new CountDownTimer(240000, 1000) { // adjust the milli seconds here
public void onTick(long millisUntilFinished) {
String time=""+String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes( millisUntilFinished),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)));
Toast.makeText(context, time, Toast.LENGTH_SHORT).show();
}
public void onFinish() {
Intent i=new Intent(context,MainActivity.class);
context.startActivity(i);
Toast.makeText(context, "oops! Pls check your net connection", Toast.LENGTH_SHORT).show();
}
}.start();
Upvotes: 0
Views: 55
Reputation: 405
Create A Global Variable of Timer
CountDownTimer mTimer = null;
on PreExecute() write
@Override
protected void onPreExecute()
{
mTimer = new CountDownTimer(240000, 1000) { // adjust the milli seconds here
public void onTick(long millisUntilFinished) {
String time=""+String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes( millisUntilFinished),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)));
Toast.makeText(context, time, Toast.LENGTH_SHORT).show();
}
public void onFinish() {
Intent i=new Intent(context,MainActivity.class);
context.startActivity(i);
Toast.makeText(context, "oops! Pls check your net connection", Toast.LENGTH_SHORT).show();
}
}.start();
}
now on postExecute() write
@Override
protected void onPostExecute()
{
mTimer.cancel();
}
Upvotes: 1