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

Android 驗證碼倒計時的兩種實現:CountDownTimer 與 Handler+Thread

編輯:關於 Android 程式設計

之前聊過順時針計時器的寫法,那種方式在錄屏、計時類場景裡很常用。這次換個方向,講講倒計時——最典型的落地場景就是「獲取短信驗證碼」按鈕。

本文面向初學者,代碼刻意寫得直白,重點放在思路和幾個容易踩坑的地方。

方案一:直接繼承 CountDownTimer(推薦)

CountDownTimer 是系統提供的倒計時類,繼承時必須調用它的構造方法並實現兩個抽象方法:

  • 構造參數一:millisInFuture,倒計時總時長;
  • 構造參數二:countDownInterval,回調間隔;
  • onTick(long millisUntilFinished):剩餘時間的週期回調;
  • onFinish():倒計時結束後的收尾邏輯。

注意所有時間單位都是毫秒,顯示成「秒」時記得除以 1000。

另一個容易忽略的點:如果用內部類持有 Activity 引用,內存洩漏風險是存在的,因此要在 onDestroy() 裡置空對象,並避免重複 new。

方案二:Handler + Thread

老方法同樣能用。子線程裡循環 sleep 並發消息,主線程的 Handler 更新 UI。這裡的關鍵是給循環加一個「開關」標誌位:Activity 銷毀時把它置為 false,讓子線程自然退出,否則線程會一直空轉。

核心代碼

package com.example.nanchen.timerdemo;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    private Button mBtnGetCode;
    private TimeCount mTimeCount;
    private Button mBtnGetCode2;
    private boolean timeFlag = true;

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

        mBtnGetCode = (Button) findViewById(R.id.main_btn_get_code);
        mBtnGetCode.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mTimeCount = null;
                mTimeCount = new TimeCount(60 * 1000, 1000);
                mTimeCount.start();
            }
        });

        mBtnGetCode2 = (Button) findViewById(R.id.main_btn_get_code_2);
        mBtnGetCode2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mBtnGetCode2.setClickable(false);
                mBtnGetCode2.setBackgroundColor(getResources().getColor(R.color.btn_unable));
                timeFlag = true;
                new Thread() {
                    @Override
                    public void run() {
                        super.run();
                        for (int i = 59; i >= 0 && timeFlag; i--) {
                            try {
                                sleep(1000);
                                Message msg = Message.obtain();
                                msg.what = i;
                                mHandler.sendMessage(msg);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }.start();
            }
        });
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what > 0) {
                mBtnGetCode2.setText("(" + msg.what + ")秒後重試");
            } else {
                mBtnGetCode2.setText("獲取驗證碼");
                mBtnGetCode2.setClickable(true);
                mBtnGetCode2.setBackgroundColor(getResources().getColor(R.color.colorAccent));
            }
        }
    };

    /** Activity 銷毀時把所有引用置空,避免內存洩漏 */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mTimeCount = null;
        timeFlag = false;
    }

    private class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mBtnGetCode.setClickable(false);
            mBtnGetCode.setBackgroundColor(getResources().getColor(R.color.btn_unable));
            mBtnGetCode.setText("(" + millisUntilFinished / 1000 + ")秒後重試");
        }

        @Override
        public void onFinish() {
            mBtnGetCode.setClickable(true);
            mBtnGetCode.setText("獲取驗證碼方式1");
            mBtnGetCode.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
        }
    }
}

布局很簡單,兩個按鈕加一條分隔線:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.nanchen.timerdemo.MainActivity">

    <Button
        android:layout_marginTop="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/main_btn_get_code"
        android:text="獲取驗證碼方式1"
        android:background="@color/colorPrimaryDark"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:id="@+id/main_line1"
        android:background="@color/btn_unable"
        android:layout_below="@+id/main_btn_get_code"
        android:layout_marginTop="10dp"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/main_line1"
        android:layout_marginTop="10dp"
        android:text="獲取驗證碼方式2"
        android:id="@+id/main_btn_get_code_2"
        android:background="@color/colorAccent"/>
</RelativeLayout>

兩種方式對比下來,CountDownTimer 代碼量更少、計時精度由系統保證,日常開發首選它;Handler + Thread 的好處是邏輯完全可控,適合需要與其他異步任務協調的場景。

源碼地址:https://github.com/nanchen2251/TimerDemo

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