Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 入門第一彈:用 Timer 與 Handler 做一個倒計時器

編輯:關於 Android 程式設計

坦白說,作為系列的第一篇,這個例子確實有點樸素。但入門總要從最小可用的東西開始寫起,先把「界面 + 邏輯 + 線程通信」這條主線跑通,後面才有底氣寫更複雜的東西。

界面佈局

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/etInputNum"
        android:layout_width="197dp"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="number" />

    <Button
        android:id="@+id/btnGetNum"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="獲取計時計數" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="109dp">

        <Button
            android:id="@+id/btnStartCount"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_centerVertical="true"
            android:layout_marginStart="56dp"
            android:text="開始計時" />

        <Button
            android:id="@+id/btnStopCount"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignTop="@+id/btnStartCount"
            android:layout_marginEnd="59dp"
            android:text="結束計時" />
    </RelativeLayout>

    <TextView
        android:id="@+id/tvOutputNum"
        android:layout_width="match_parent"
        android:layout_height="208dp" />
</LinearLayout>

核心代碼

package myapplication.nomasp.com.timer;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends Activity implements View.OnClickListener {

    private EditText etInputNum;
    private Button btnGetNum, btnStartCount, btnStopCount;
    private TextView tvOutputNum;

    private int i = 0;
    private Timer timer = null;
    private TimerTask task = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        etInputNum = (EditText) findViewById(R.id.etInputNum);
        btnGetNum = (Button) findViewById(R.id.btnGetNum);
        btnStartCount = (Button) findViewById(R.id.btnStartCount);
        btnStopCount = (Button) findViewById(R.id.btnStopCount);
        tvOutputNum = (TextView) findViewById(R.id.tvOutputNum);

        btnGetNum.setOnClickListener(this);
        btnStartCount.setOnClickListener(this);
        btnStopCount.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnGetNum:
                // 把輸入框的數字取出來作為倒計時初始值
                tvOutputNum.setText(etInputNum.getText().toString());
                i = Integer.parseInt(etInputNum.getText().toString());
                break;
            case R.id.btnStartCount:
                startTime();
                break;
            case R.id.btnStopCount:
                stopTime();
                break;
            default:
                break;
        }
    }

    // 子線程不能直接更新 UI,必須透過 Handler 把消息拋回主線程
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            tvOutputNum.setText(msg.arg1 + "");
            startTime();
        }
    };

    public void startTime() {
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                i--;
                Message message = mHandler.obtainMessage();
                message.arg1 = i;
                mHandler.sendMessage(message);
            }
        };
        timer.schedule(task, 1000);
    }

    public void stopTime() {
        timer.cancel();
    }
}

這個小例子值得記住的三件事

  1. 線程分工:計時任務跑在 Timer 的後台線程裡,界面刷新必須通過 Handler 切換回主線程,這是 Android 的硬性規範。
  2. Message 的輕量傳值:這裡用 msg.arg1 傳遞整數,比裝 Bundle 更省開銷;代碼中每次循環都 new 一個新的 Message 也是必要的,複用同一個 Message 反覆發送會出現異常。
  3. 資源釋放:stopTime() 裡調用 timer.cancel(),Activity 銷毀時也應記得取消定時任務,否則容易導致內存洩漏。

後續可以繼續改進的方向不少:用 CountDownTimer 替代 Timer 更貼合語義,把倒計時封裝成自定義 View,或者處理 Activity 旋轉後的狀態保持。加油。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved