यदि आप नीचे दिए गए कोड का उपयोग करते हैं (जैसा कि स्वीकृत उत्तर में बताया गया है),
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
//here you can have your logic to set text to edittext
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
यदि आप इस कोड का उपयोग करते हैं तो गतिविधि के उदाहरण की मेमोरी लीक हो जाएगी, यदि आप संदर्भों को ध्यान से साफ नहीं करते हैं।
निम्नलिखित कोड का उपयोग करें
//Declare timer
CountDownTimer cTimer = null;
//start timer function
void startTimer() {
cTimer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
}
};
cTimer.start();
}
//cancel timer
void cancelTimer() {
if(cTimer!=null)
cTimer.cancel();
}
आपको cTtimer.cancel () को कॉल करने की आवश्यकता होती है जब भी ओन्डिंग एक्टिविटी / फ्रैगमेंट में onDestroy () / onDestroyView () को कहा जाता है।