編輯:關於 Android 程式設計
之前聊過順時針計時器的寫法,那種方式在錄屏、計時類場景裡很常用。這次換個方向,講講倒計時——最典型的落地場景就是「獲取短信驗證碼」按鈕。
本文面向初學者,代碼刻意寫得直白,重點放在思路和幾個容易踩坑的地方。

CountDownTimer 是系統提供的倒計時類,繼承時必須調用它的構造方法並實現兩個抽象方法:
millisInFuture,倒計時總時長;countDownInterval,回調間隔;onTick(long millisUntilFinished):剩餘時間的週期回調;onFinish():倒計時結束後的收尾邏輯。注意所有時間單位都是毫秒,顯示成「秒」時記得除以 1000。
另一個容易忽略的點:如果用內部類持有 Activity 引用,內存洩漏風險是存在的,因此要在 onDestroy() 裡置空對象,並避免重複 new。
老方法同樣能用。子線程裡循環 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
透過 Xposed 修改微信運動步數的實作教學
前言:Zygote 是 Android 的核心機制,每開啟一個 App,Zygote 就會 fork 出一個虛擬機實例來執行。有了 Xposed 框架,我們便能運用 An
Android 仿今日頭條頻道移動:ListView Item 動畫遷移實作
效果與思路這個範例模擬資訊類應用中常見的頻道管理效果:上方與下方各有一個 ListView,當使用者點擊下方項目時,該項目會以動畫方式移動到上方清單的最後一項,同時下方清
Android 簡易實戰教程(十八):ListView 顯示與 SimpleAdapter 入門
ListView 的適配器有好幾種:ArrayAdapter、BaseAdapter、SimpleAdapter 等等。本篇先熱身,用最簡單的 SimpleAdapter
Android OnScrollListener 事件觸發順序與次數實測分析
關於 OnScrollListener,最常被搞混的就是兩個回呼方法到底誰先誰後、各觸發幾次。仔細實測之後,可以整理出下面這個結論。 事件觸發順序 new AbsLis