Android 中的時間驅動機制 (TimerTask)

Android

簡介

使用方法

開發工具

開始寫程式

視覺化介面

視覺元件

對話元件

核心物件

事件處理

資料儲存

查詢功能

影音功能

繪圖功能

網路功能

衛星地圖

特殊功能

資源管理

裝置管理

系統核心

問題與回答

刷機升級

常用軟體

Eclipse

教學錄影

訊息

相關網站

參考文獻

最新修改

簡體版

English

專案下載:Clock.zip

程式範例:數位小時鐘

檔案:layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView android:id="@+id/TextViewTime" 
    android:layout_width="100px" 
    android:layout_height="fill_parent" 
    android:text="Hello!"
    android:layout_x="120px"
    android:layout_y="150px"    
    android:textSize="24sp"    
    />
</AbsoluteLayout>

檔案:Clock.java

package ccc.android;
 
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.Time;
import android.widget.TextView;
 
public class Clock extends Activity {
    protected static final int CLOCK_UPDATE = 0x101;
    TextView textViewTime;
 
    Handler clockHandler = new Handler() {  
        public void handleMessage(Message msg) {   
             switch (msg.what) {   
                  case Clock.CLOCK_UPDATE:   
                       textViewTime.setText(now());
                       textViewTime.invalidate();  
                       break;
             }   
             super.handleMessage(msg);   
        }   
   };    
 
   /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        textViewTime = (TextView) findViewById(R.id.TextViewTime);
        textViewTime.setText(now());
        new Thread(new clockThread()).start();  
    }
 
    public String now() {
        Time time = new Time();
        time.setToNow();
        return String.format("%02d:%02d:%02d", time.hour, time.minute, time.second);
    }
 
    class clockThread implements Runnable {   
        public void run() {  
             while (!Thread.currentThread().isInterrupted()) {    
 
                  Message message = new Message();   
                  message.what = Clock.CLOCK_UPDATE;   
 
                  Clock.this.clockHandler.sendMessage(message);   
                  try {   
                       Thread.sleep(100);    
                  } catch (InterruptedException e) {   
                       Thread.currentThread().interrupt();   
                  }   
             }   
        }   
   }
}

執行結果

Clock.png

改良

如果使用 Timer 與 scheduleAtFixedRate() 函數,則上列程式可以簡化如下。

package ccc.android;
 
import java.util.Timer;
import java.util.TimerTask;
 
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.Time;
import android.widget.TextView;
 
public class ClockTimer extends Activity {
    TextView textViewTime;
 
    private Handler mHandler = new Handler(){  
 
        public void handleMessage(Message msg) {  
            switch (msg.what) {  
            case 1:  
                textViewTime.setText(now());
                break;  
            }  
        };  
    };  
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        textViewTime = (TextView) findViewById(R.id.TextViewTime);
        textViewTime.setText(now());
 
        Timer timer = new Timer();  
        timer.scheduleAtFixedRate(new ClockTask(), 1, 1000);          
    }
 
    public String now() {
        Time time = new Time();
        time.setToNow();
        return String.format("%02d:%02d:%02d", time.hour, time.minute, time.second);
    }
 
    private class ClockTask extends TimerTask {  
        @Override  
        public void run() {
            Message message = new Message();  
            message.what = 1;  
            mHandler.sendMessage(message);
        }     
    }    
}

參考文獻

  1. Android Timer的用法示例 — http://www.javaeye.com/topic/422972
  2. http://developer.android.com/reference/java/util/TimerTask.html
  3. http://developer.android.com/reference/android/os/Handler.html
  4. Android底層結構:SDK Service線程知多少?(1), By 高煥堂 — http://www.android1.net/Topic.aspx?BoardID=11&TopicID=775
  5. Android中使用定时器TimerTask类介绍 — http://cnmsdn.com/html/201010/1287044888ID8228.html

Facebook

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License