به این منظور از یک کلاس Counter استفاده میکنیم.
import android.os.Handler;
public class Counter {
private Handler handler;
private int time;
private int min;
private int sec;
private String minPrefix;
private String secPrefix;
private iCounter counter;
public Counter init() {
this.handler = new Handler();
return this;
}
public Counter time(int time) {
this.time = time;
return this;
}
public Counter listener(iCounter counter) {
this.counter = counter;
return this;
}
public Counter startTime() {
CounterTime();
return this;
}
public void stopTime() {
this.time = 0;
}
public boolean isRun() {
if (time > 0) {
return true;
}
return false;
}
public interface iCounter {
void counterTime(String time);
void counterFinish();
}
private void CounterTime() {
if (time > 0) {
handler.postDelayed(new Runnable() {
public void run() {
time--;
min = (int) Math.floor(time / 60);
sec = time % 60;
minPrefix = "";
if (min < 10) {
minPrefix = "0";
}
secPrefix = "";
if (sec < 10) {
secPrefix = "0";
}
if (time > 0) {
counter.counterTime(String.valueOf(minPrefix + min + ":" + secPrefix + sec));
} else {
counter.counterTime(String.valueOf("00:00"));
}
CounterTime();
}
}, 1000);
} else {
counter.counterFinish();
}
}
}
در زمان استفاده از این کلاس به این صورت مینویسیم :
private Counter counter;
if (counter != null && counter.isRun()) {
return;
}
counter = new Counter().init().time(120).listener(new Counter.iCounter() {
@Override
public void counterTime(String time) {
txtResendSms.setText(time);
}
@Override
public void counterFinish() {
}
}).startTime();
در این کد مقدار Timer به ثانیه میباشد که 120 قرار گرفته است .
نظرات (۰)