CountDownTimer source code analysis, countdowntimer source code

Source: Internet
Author: User

CountDownTimer source code analysis, countdowntimer source code

Countdown function, for example, countdown to sending SMS verification codes.

1 public class CountDownTimerActivity extends Activity {2 3 private Button mSend; 4 private SendCountMessage mCountMessage; 5 6 @ Override 7 protected void onCreate (Bundle savedInstanceState) {8 super. onCreate (savedInstanceState); 9 this. setContentView (R. layout. activity_countdown); 10 11 mCountMessage = new SendCountMessage (); 12 mSend = (Button) findViewById (R. id. sendCode); 13 mSend. setOnClickListen Er (new View. onClickListener () {14 @ Override15 public void onClick (View v) {16 mSend. setClickable (false); 17 // start to execute the countdown function 18 mCountMessage. start (); 19} 20}); 21} 22 23 24/*** we inherit this abstract class and set the total countdown time, and the interval is 26 * and the onTick and onFinish Methods 27 */28 class SendCountMessage extends CountDownTimer {29 30/*** 31 * are rewritten. Here we also need to set two parameters: 32 * First parameter: indicates the total countdown time 33 * second parameter: indicates the countdown interval, for example, whether we use one second or two seconds 34 */35 public SendCountM Essage () {36 super (60000,100 0); 37} 38 39/** 40 * This method indicates that this method is called at the specified interval in the constructor. 41 * For example, if we set the interval to 1 second, countDownTimer42 * calls the onTick method every second. 43 * @ param millisUntilFinished indicates 44 */45 public void onTick (long millisUntilFinished) {46 mSend. setText (millisUntilFinished/1000 + "resend after seconds"); 47} 48 49/** 50 * Here it indicates that the countdown is completed and 51 */52 public void onFinish () {53 mSend. setClickable (true); 54} 55} 56 57 @ Override58 protected void onDestroy () {59 super. onDestroy (); 60/** 61 *, We need to cancel CountDownTimer, because if the countdown timer is not canceled 62 * when the interface is destroyed, it will continue running in the background until the end of the countdown ends, 63 * in this way, in order to avoid problems, we need to cancel it here and let the system gc the variable. 64 */65 if (mCountMessage! = Null) {66 mCountMessage. cancel (); 67 mCountMessage = null; 68} 69} 70}

Interface layout:

1 <? Xml version = "1.0" encoding = "UTF-8"?> 2 <LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" 3 android: layout_width = "match_parent" 4 android: layout_height = "match_parent" 5 android: orientation = "vertical"> 6 7 ........ 8 9 <LinearLayout10 android: layout_width = "fill_parent" 11 android: layout_height = "wrap_content" 12 android: layout_marginBottom = "20dip" 13 android: layout_marginLeft = "10dip" 14 android: layout_marginRight = "10dip" 15 android: layout_marginTop = "20dip"> 16 17 <EditText18 android: layout_width = "0dip" 19 android: layout_height = "wrap_content" 20 android: layout_weight = "1" 21 android: inputType = "number" 22 android: hint = "Enter the verification code"/> 23 24 <Button25 android: id = "@ + id/sendCode" 26 android: layout_width = "wrap_content" 27 android: layout_height = "wrap_content" 28 android: text = "Send verification code" 29 android: textSize = "18sp"/> 30 31 </LinearLayout> 32 33 </LinearLayout>

When we do not need the countdown function, we must call the cancel () method to cancel it. Otherwise, it will continue to be executed when the page is destroyed, memory leakage may occur.

Code Analysis
1 public CountDownTimer (long millisInFuture, long countDownInterval) {2 rows = millisInFuture; 3 rows = countDownInterval; 4} 5 6 public synchronized final CountDownTimer start () {7 mCancelled = false; 8 if (mMillisInFuture <= 0) {9 onFinish (); 10 return this; 11} 12 // calculate the end millisecond value through the current start time + the total countdown time. 13 mStopTimeInFuture = SystemClock. elapsedRealtime () + mMillisInFuture; 14 // then send a message to mHandler15 mHandler. sendMessage (mHandler. obtainMessage (MSG); 16 return this; 17}

Code in mHandler:

1 // handles counting down 2 private Handler mHandler = new Handler () {3 4 @ Override 5 public void handleMessage (Message msg) {6 7 synchronized (CountDownTimer. this) {8 // if the user calls the cancellation method proactively, return 9 if (mCancelled) {10 return; 11} 12 13 // Step 1: first, judge the difference between the end time and the current time. 14 final long millisLeft = mStopTimeInFuture-SystemClock. elapsedRealtime (); 15 16 // condition 1: If the value is smaller than or equal to 0, the process is over. 17 if (millisLeft <= 0) {18 onFinish (); 19} else if (millisLeft <mCountdownInterval) {20 // no tick, just delay until done21 // condition 2: if the end time is less than the preset interval value 22 // A millisLeft delayed message is sent at this time 23 sendMessageDelayed (obtainMessage (MSG), millisLeft ); 24} else {25 long lastTickStart = SystemClock. elapsedRealtime (); 26 // call our abstract method and call back the end time value as a parameter. 27 onTick (millisLeft ); 28 29 // take into account user's onTick taking time to execute30 long delay = lastTickStart + mCountdownInterval-SystemClock. elapsedRealtime (); 31 32 // special case: user's onTick took more than interval to33 // complete, skip to next interval34 while (delay <0) delay + = mCountdownInterval; 35 36 // send a delayed message, with the interval set for our mCountdownInterval message going out 37 sendMessageDelayed (obtainMessage (MSG), delay); 38} 39} 40} 41 };

An internal Handler object will be created before the constructor is created, which is mainly used for scheduled message sending. When we callstart()The method sends a Handler message, which is processed in mHandler.

After receiving the message, Handler compares it with the set interval value and sends a delayed message.

public synchronized final void cancel() {    mCancelled = true;    mHandler.removeMessages(MSG);}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.