android倒計時功能的實現(CountDownTimer)

轉自  http://blog.csdn.net/lilu_leo/article/details/6941724 

在逛論壇的時候,看到一個網友提問,說到了CountDownTimer這個類,從名字上面大家就可以看出來,記錄下載時間。將後臺線程的創建和Handler隊列封裝成一個方便的類調用。

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

[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. new CountdownTimer(300001000) {  
  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。

[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  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);  
  18.         mc = new MyCount(300001000);  
  19.         mc.start();  
  20.     }//end func  
  21.   
  22.     /*定義一個倒計時的內部類*/  
  23.     class MyCount extends CountDownTimer {     
  24.         public MyCount(long millisInFuture, long countDownInterval) {     
  25.             super(millisInFuture, countDownInterval);     
  26.         }     
  27.         @Override     
  28.         public void onFinish() {     
  29.             tv.setText("finish");        
  30.         }     
  31.         @Override     
  32.         public void onTick(long millisUntilFinished) {     
  33.             tv.setText("請等待30秒(" + millisUntilFinished / 1000 + ")...");     
  34.             Toast.makeText(NewActivity.this, millisUntilFinished / 1000 + "", Toast.LENGTH_LONG).show();//toast有顯示時間延遲       
  35.         }    
  36.     }     
  37. }  

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

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


發佈了48 篇原創文章 · 獲贊 33 · 訪問量 31萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章