android應用開發中常常會用到定時器,不可避免的需要用到 TimerTask 定時器任務這個類
例如在Android平台中需要反複按周期執行方法可以使用Java上自帶的TimerTask類,TimerTask相對于Thread來說對于資源消耗的更低,除了使用Android自帶的AlarmManager,使用Timer定時器是一種更好的解決方法。下面我們通過一個簡單的Demo來講解Timer和TimerTask的使用。首先先看項目運作效果:
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiInBnauAnRFllM0MjMzgzMxMTMfBzM1IzM3gzLcBjMvwFOwETMwIzLcRnbl1GajFGd0F2LcRXZu5ibkN3YukGavw1LcpDc0RHaiojIsJye.jpg)
以上就是我們今天要實作的。看起來簡單吧。呵呵,廢話不多說了,進入正題。
1、首先建立一個Android項目工程,這是必須的。在這裡我命名其為TimeDemo。
2、修改主布局檔案main.xml,具體代碼如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id="@+id/myButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="開始倒計時"
/>
<TextView
android:id="@+id/myTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
這裡就不多講了,好簡單,就兩個常用的控件。
3、修改Activiyt類,我們要做的工作都放在這個主程式中。具體代碼如下:
public class MyActivity extends Activity {
TextView text;
Button button;
Timer timer;
int i=10;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text=(TextView)findViewById(R.id.myTextView);
final Handler myHandler=new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
if(msg.what>0){
/*這裡要注意下,msg.what是一個整形型數字,
* 而setText(字元),是以要再前面加上""*/
text.setText(""+msg.what);
}
else{
text.setText("開始");
timer.cancel();
}
}
};
button=(Button)findViewById(R.id.myButton);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// 定義計時器
timer=new Timer();
/*定義計劃任務,根據參數的不同可以完成以下種類的工作:
* 在固定時間執行某任務,在固定時間開始重複執行某任務,
* 重複時間間隔可控,在延遲多久後執行某任務,在延遲多久
* 後重複執行某任務,重複時間間隔可控
*/
timer.schedule(new TimerTask() {
// TimerTask 是個抽象類,實作的是Runable類
@Override
public void run() {
// TODO Auto-generated method stub
// Message message=new Message();
// message.what=i--;
i--;
myHandler.sendEmptyMessage(i);
}
}, 1000, 1000);
}
});
}
}
程式中需要注意的地方,我都寫明了。在這裡就不啰嗦了。呵呵。
4、編輯好,儲存。單擊項目執行之,便可以了。
呵呵,當我們單擊開始倒計時按鈕時。在按鈕下面的TextView出現相應的數字。當小于0時,就會提示“開始”。
今天就到這裡。