CountDownTimer 源碼分析,countdowntimer源碼

來源:互聯網
上載者:User

CountDownTimer 源碼分析,countdowntimer源碼

倒計時的功能,比如說:傳送簡訊驗證碼倒計時。

 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.setOnClickListener(new View.OnClickListener() {14             @Override15             public void onClick(View v) {16                 mSend.setClickable(false);17                 //開始執行倒計時的功能18                 mCountMessage.start();19             }20         });21     }22 23 24     /**25      * 我們繼承這個抽象類別,然後設定好總共的倒計時的時間,以及間隔的時間26      * 並且重寫 onTick和onFinish方法27      */28     class SendCountMessage extends CountDownTimer {29 30         /**31          * 這裡我們還需要設定兩個參數:32          * 第一個參數:表示我們倒計時的總時間33          * 第二個參數:表示我們倒計時的間隔,比如說我們是按一秒數還是二秒34          */35         public SendCountMessage() {36             super(60000, 1000);37         }38 39         /**40          * 該方法表示會在構造方法中設定的間隔時間下調用這個方法的。41          * 比如說我們設定了間隔時間為1秒的話,那麼CountDownTimer42          * 將會每個一秒的時間調用 onTick方法一下43          * @param millisUntilFinished 表示距離倒計時結束的時間44          */45         public void onTick(long millisUntilFinished) {46             mSend.setText(millisUntilFinished/1000 + " 秒後重發");47         }48 49         /**50          * 這裡表示倒計時完成結束了51          */52         public void onFinish() {53             mSend.setClickable(true);54         }55     }56 57     @Override58     protected void onDestroy() {59         super.onDestroy();60         /**61          * 最後在這裡的時候,我們需要將CountDownTimer取消掉,因為如果我們在銷毀介面的時候62          * 還沒有取消該倒計時器的話,它還會一直在後台不斷的跑的直到結束倒計最後才會結束的,63          * 這樣子為了以免出現問題,我們這裡需要取消掉,並且讓系統gc該變數。64          */65         if(mCountMessage != null) {66             mCountMessage.cancel();67             mCountMessage = null;68         }69     }70 }

介面布局:

 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="請輸入驗證碼" />23 24         <Button25             android:id="@+id/sendCode"26             android:layout_width="wrap_content"27             android:layout_height="wrap_content"28             android:text="發送驗證碼"29             android:textSize="18sp" />30 31     </LinearLayout>32 33 </LinearLayout>

當我們不需要使用倒計時功能的時候,一定要要調用cancel()方法取消掉,不然它還會在我們頁面銷毀的時候繼續執行的,很有可能會導致記憶體流失的問題

程式碼分析
 1 public CountDownTimer(long millisInFuture, long countDownInterval) { 2     mMillisInFuture = millisInFuture; 3     mCountdownInterval = countDownInterval; 4 } 5  6 public synchronized final CountDownTimer start() { 7     mCancelled = false; 8     if (mMillisInFuture <= 0) { 9         onFinish();10         return this;11     }12     //通過當前開始的時間 + 倒計時的總時間來計算出結束的毫秒值13     mStopTimeInFuture = SystemClock.elapsedRealtime() + mMillisInFuture;14     //然後發送一個message訊息給mHandler15     mHandler.sendMessage(mHandler.obtainMessage(MSG));16     return this;17 }

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            //如果使用者主動調用了取消方法,則返回 9             if (mCancelled) {10                 return;11             }12 13             //第一步:首先判斷結束的時間跟目前時間的差。14             final long millisLeft = mStopTimeInFuture - SystemClock.elapsedRealtime();15 16             //條件一: 如果小於等於0了,說明結束了。17             if (millisLeft <= 0) {18                 onFinish();19             } else if (millisLeft < mCountdownInterval) {20                 // no tick, just delay until done21                 //條件二: 如果距離結束的時間小於我們設定的間隔時間值的時候22                 //        這個時候就發送一個millisLeft延時的訊息23                 sendMessageDelayed(obtainMessage(MSG), millisLeft);24             } else {25                 long lastTickStart = SystemClock.elapsedRealtime();26                 //調用我們的抽象方法,並且將距離結束的時間值當作參數回調出去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                 //發送一個延時的,時間間隔為我們設定的mCountdownInterval的訊息出去37                 sendMessageDelayed(obtainMessage(MSG), delay);38             }39         }40     }41 };

    在建立建構函式之前會建立一個內部的Handler對象,主要是用於定時發送訊息用的。當我們調用start()方法的時候會發送一個Handler訊息出來,這個時候會在mHandler中進行處理。

當Handler收到訊息之後就會去跟設定的時間間隔值進行一個比對,然後就發送一個延時的訊息。

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

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.