編輯:關於 Android 程式設計
以前寫倒數,多半是自己開一條線程 sleep 再回主線程更新 UI,麻煩又容易出錯。翻資料時發現系統其實早就提供了 android.os.CountDownTimer,於是果斷拋棄舊做法。這個類只要給兩個參數就能運作,還免費附帶取消與重新開始的能力。
new MyCountDownTimer(30000, 1000);
millisInFuture:以毫秒為單位的總時長,30000 就是 30 秒。countDownInterval:呼叫 onTick() 的間隔,1000 代表每秒回呼一次。mc.start() 開始;mc.cancel() 取消。只需要覆寫 onTick()(每次間隔觸發)與 onFinish()(時間到)。
package com.example.daojishi;
import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private MyCountDownTimer mc;
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.show);
mc = new MyCountDownTimer(30000, 1000);
mc.start();
}
public void oncancel(View view) {
Toast.makeText(MainActivity.this, "取消", Toast.LENGTH_LONG).show();
mc.cancel();
}
public void restart(View view) {
Toast.makeText(MainActivity.this, "重新開始", Toast.LENGTH_LONG).show();
mc.start();
}
/** 繼承 CountDownTimer,重寫 onTick() 與 onFinish() */
class MyCountDownTimer extends CountDownTimer {
/**
* @param millisInFuture 倒數總毫秒數,1000 即 1 秒
* @param countDownInterval 每隔多少毫秒呼叫一次 onTick()
*/
public MyCountDownTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onFinish() {
tv.setText("done");
}
@Override
public void onTick(long millisUntilFinished) {
Log.i("MainActivity", millisUntilFinished + "");
tv.setText("倒計時(" + millisUntilFinished / 1000 + ")...");
}
}
}
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/button1"
android:onClick="oncancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/show"
android:layout_below="@+id/show"
android:layout_marginLeft="50dp"
android:layout_marginTop="106dp"
android:text="cancel" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_below="@+id/button1"
android:layout_marginTop="63dp"
android:onClick="restart"
android:text="restart" />
</RelativeLayout>
讀一遍源碼會發現它的實作比想像中簡潔——本質上就是一個 Handler 加上「下次該觸發的時間點」。
package android.os;
import android.util.Log;
/**
* Schedule a countdown until a time in the future, with
* regular notifications on intervals along the way.
*/
public abstract class CountDownTimer {
/** 倒數結束的目標時間(毫秒) */
private final long mMillisInFuture;
/** 回呼的間隔(毫秒) */
private final long mCountdownInterval;
private long mStopTimeInFuture;
public CountDownTimer(long millisInFuture, long countDownInterval) {
mMillisInFuture = millisInFuture;
mCountdownInterval = countDownInterval;
}
/** 取消倒數 */
public final void cancel() {
mHandler.removeMessages(MSG);
}
/** 開始倒數 */
public synchronized final CountDownTimer start() {
if (mMillisInFuture <= 0) {
onFinish();
return this;
}
mStopTimeInFuture = SystemClock.elapsedRealtime() + mMillisInFuture;
mHandler.sendMessage(mHandler.obtainMessage(MSG));
return this;
}
/** 每次間隔觸發,剩餘毫秒數由參數帶入 */
public abstract void onTick(long millisUntilFinished);
/** 時間到 */
public abstract void onFinish();
private static final int MSG = 1;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
synchronized (CountDownTimer.this) {
final long millisLeft = mStopTimeInFuture - SystemClock.elapsedRealtime();
if (millisLeft <= 0) {
onFinish();
} else if (millisLeft < mCountdownInterval) {
// 不足一個間隔,直接等到結束即可
sendMessageDelayed(obtainMessage(MSG), millisLeft);
} else {
long lastTickStart = SystemClock.elapsedRealtime();
onTick(millisLeft);
// 把 onTick() 本身的執行時間也計算進去
long delay = lastTickStart + mCountdownInterval
- SystemClock.elapsedRealtime();
// 若 onTick() 執行太久,直接跳到下一個間隔
while (delay < 0) {
delay += mCountdownInterval;
}
sendMessageDelayed(obtainMessage(MSG), delay);
}
}
}
};
}
源碼中有兩個細節值得記住:一是 onTick() 的呼叫彼此同步,前一次沒跑完,後一次不會插隊;二是它會把 onTick() 的執行耗時從下次延遲中扣除,所以即使回呼裡做事稍慢,總時長也不會被拖長。反過來說,如果 onTick() 裡放了太重的運算,UI 一樣會卡,這點和用不用 CountDownTimer 無關。
Android 常見錯誤集錦(持續更新中)
本文彙整了日常 Android 開發中經常遇到的各種錯誤及其解決方案,方便日後查閱對照。Eclipse 真機無法列印 log 資訊系統環境:Windows7 64 位解決
騰訊WiFi管家怎麼連上別人分享的熱點?操作教學與法律提醒
騰訊WiFi管家和「WiFi萬能鑰匙」是同一類型的工具,本質上並不是破解加密,而是把使用者自願分享的熱點密碼集中成一份資料庫,讓手機在訊號範圍內可以一鍵連上。這也是為什麼
Android 藍牙入門(一):基本概念與硬件接口
前言Android 藍牙系統涉及硬件、驅動、協議棧與應用層等多個層面。本文先從基本概念與硬件接口切入,說明 AP、BP、CP、RF 等常見名詞,並介紹藍牙模組常見的 UA
ViewPager 頂部導覽列聯動實作:當 Tab 數量超過螢幕寬度
先前寫過 TabLayout 與 ViewPager 的聯動效果,但那是建立在「標題數量不多、一row 剛好放得下」的前提上。一旦項目變多、總寬度超過螢幕,固定模式的 T