Android實現倒計時之使用CountDownTimer

來源:互聯網
上載者:User

CountDownTimer這個類,從名字上面大家就可以看出來,記錄下載時間。將後台線程的建立和Handler隊列封裝成為了一個方便的類調用。

 查看了一下官方文檔,這個類及其簡單,只有四個方法,上面都涉及到了onTick,onFinsh、cancel和start。其中前面兩個是抽象方法,所以要重寫一下。
 下面是官方給的一個小例子:

1. new CountdownTimer(30000, 1000) {  

2.     public void onTick(long millisUntilFinished) {  

3.         mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);  

4.     }  

5.     public void onFinish() {  

6.         mTextField.setText("done!");  

7.     }  

8.  }.start();  

下面是修改後的一個Demo

1. package cn.demo;  

2.   

3. import android.app.Activity;  

4. import android.os.Bundle;  

5. import android.content.Intent;  

6. import android.os.CountDownTimer;  

7. import android.widget.TextView;  

8. import android.widget.Toast;  

9. public class NewActivity extends Activity {  

10.     private MyCount mc;  

11.     private TextView tv;  

12.     @Override  

13.     protected void onCreate(Bundle savedInstanceState) {  

14.         // TODO Auto-generated method stub  

15.         super.onCreate(savedInstanceState);  

16.         setContentView(R.layout.main);  

17.         tv = (TextView)findViewById(R.id.show);  

1.         mc = new MyCount(30000, 1000);  

2.         mc.start();  

3.     }

4.   

5.     /*定義一個倒計時的內部類*/  

6.     class MyCount extends CountDownTimer {     

7.         public MyCount(long millisInFuture, long countDownInterval) {     

8.             super(millisInFuture, countDownInterval);     

9.         }     

10.         @Override     

11.         public void onFinish() {     

12.             tv.setText("finish");        

13.         }     

14.         @Override     

15.         public void onTick(long millisUntilFinished) {     

16.             tv.setText("請等待30秒(" + millisUntilFinished / 1000 + ")...");     

17.             Toast.makeText(NewActivity.this, millisUntilFinished / 1000 + "", Toast.LENGTH_LONG).show();//toast有顯示時間延遲       

18.         }    

19.     }     

20. }  

主要是重寫onTick和onFinsh這兩個方法,onFinish()中的代碼是計時器結束的時候要做的事情;onTick(Long m)中的代碼是你倒計時開始時要做的事情,參數m是直到完成的時間,構造方法MyCount()中的兩個參數中,前者是倒計的時間數,後者是倒計每秒中間的間隔時間,都是以毫秒為單位。例如要倒計時30秒,每秒中間間隔時間是1秒,兩個參數可以這樣寫MyCount(30000,1000)。 將後台線程的建立和Handler隊列封裝成為了一個方便的類調用。

當你想取消的時候使用mc.cancel()方法就行了。

相關文章

聯繫我們

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