每日總結 - android中計時器類CountDownTimer

來源:互聯網
上載者:User

標籤:android   style   blog   color   ar   sp   div   on   art   

定時器一般用handler和線程或者timer來實現,但是android中提供了一個計時器類CountDownTimer。定時執行在一段時候後停止的倒計時,在倒計時執行過程中會在固定間隔時間得到通知(觸發onTick方法)。將後台線程的建立和Handler隊列封裝成為了一個方便的類方便開發人員調用。

 1     /* 定義一個倒計時的內部類 */ 2     class TimeCount extends CountDownTimer { 3         public TimeCount(long millisInFuture, long countDownInterval) { 4             super(millisInFuture, countDownInterval);// 參數依次為總時間長度,和計時的時間間隔 5         } 6  7         @Override 8         public void onFinish() {// 計時完畢時觸發 9             btnResend.setText("重新發送驗證碼");10             btnResend.setClickable(true);11         }12 13         @Override14         public void onTick(long millisUntilFinished) {// 計時過程顯示15             btnResend.setClickable(false);16             btnResend.setText(millisUntilFinished / 1000 + "秒");17         }18     }

 主要是重寫onTick和onFinsh這兩個方法,onFinish()中的代碼是計時器結束的時候要做的事情;onTick(Long m)中的代碼是你倒計時開始時要做的事情,參數m是直到完成的時間。

計時器建立樣本如下:

1 time = new TimeCount(12000, 1000);
1 // 重新發送驗證碼2 btnResend.setOnClickListener(new OnClickListener() {3 4     @Override5     public void onClick(View v) {6         time.start();7     }8 });

構造方法中的兩個參數中,前者是倒計的時間數,後者是倒計每秒中間的間隔時間,都是以毫秒為單位。

每日總結 - android中計時器類CountDownTimer

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.