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

Android 時分秒計時器的兩種實作方式

編輯:關於 Android 程式設計

計時器是很常出現的小需求,例如錄影時要在右上角顯示已錄多久。實作起來相當省事。

做法一:直接用 Chronometer

系統現成的 Chronometer 就是幹這個用的:

 <Chronometer android:layout_width="wrap_content" android:layout_height="wrap_content" android:format="%s" android:id="@+id/timer"/>

Java 端也只需幾行:

 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); timer = (Chronometer) findViewById(R.id.timer); } public void btnClick(View view) { timer.setBase(SystemClock.elapsedRealtime());//計時器清零 timer.start(); }

效果:

如果想顯示「時:分:秒」而不只是秒數,也只要多算一個小時位:

 public void btnClick(View view) { timer.setBase(SystemClock.elapsedRealtime()); int hour = (int) ((SystemClock.elapsedRealtime() - timer.getBase()) / 1000 / 60); timer.setFormat("0"+String.valueOf(hour)+":%s"); timer.start(); } public void stopClick(View view) { timer.stop(); }

同時把 XML 上的 format 改成對應的樣子(Chronometer 會用 %s 佔位「分:秒」那一段):

 <Chronometer android:layout_width="match_parent" android:layout_height="wrap_content" android:format="00:00:00" android:gravity="center" android:id="@+id/timer"/>

效果就與錄影畫面上方那種計時器一致了:

在外層再套一個圓圈、調一下文字顏色,觀感會更完整。

做法二:Handler/Timer + TimerTask 自己算

如果你不喜歡被 Chronometer 的行為綁住,用 Timer 加 TimerTask 自己維護計時也是常見選擇。程式碼如下:

 package com.example.nanchen.timerdemo; import android.os.SystemClock; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Chronometer; import android.widget.TextView; import java.util.Locale; import java.util.Timer; import java.util.TimerTask; public class MainActivity extends AppCompatActivity { private Chronometer timer; private Timer timer1; private TextView textView; private TimerTask timerTask; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); timer = (Chronometer) findViewById(R.id.timer); textView = (TextView) findViewById(R.id.text); timer1 = new Timer(); } public void btnClick(View view) { timer.setBase(SystemClock.elapsedRealtime()); int hour = (int) ((SystemClock.elapsedRealtime() - timer.getBase()) / 1000 / 60); timer.setFormat("0"+String.valueOf(hour)+":%s"); timer.start(); } public void stopClick(View view) { timer.stop(); } public void startClick(View view) { timerTask = new TimerTask() { int cnt = 0; @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { textView.setText(getStringTime(cnt++)); } }); } }; timer1.schedule(timerTask,0,1000); } private String getStringTime(int cnt) { int hour = cnt/3600; int min = cnt % 3600 / 60; int second = cnt % 60; return String.format(Locale.CHINA,"%02d:%02d:%02d",hour,min,second); } public void stopClick1(View view) { if (!timerTask.cancel()){ timerTask.cancel(); timer1.cancel(); } } }
 <?xml version="1.0" encoding="utf-8"?> <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="com.example.nanchen.timerdemo.MainActivity"> <Chronometer android:layout_width="match_parent" android:layout_height="wrap_content" android:format="00:00:00" android:gravity="center" android:id="@+id/timer"/> <Button android:layout_width="match_parent" android:onClick="btnClick" android:text="start" android:layout_height="wrap_content"/> <Button android:layout_width="match_parent" android:text="stop" android:onClick="stopClick" android:layout_height="wrap_content"/> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="#959393" android:layout_marginBottom="20dp" android:layout_marginTop="20dp"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="00:00:00" android:gravity="center" android:id="@+id/text"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="開始" android:onClick="startClick"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="停止" android:onClick="stopClick1"/> </LinearLayout>

Timer 版的運行效果:

怎麼選

Chronometer 的優勢是省事,基準時間用 SystemClock.elapsedRealtime()(自開機以來的毫秒數,不受使用者改系統時間影響),所以拿來計時是安全的。它的限制是格式相對固定,也沒有內建「從任意時刻起算」或「倒數」的能力。

而 Timer + TimerTask 的好處是完全自主:想從哪個秒數開始、要正算還是倒數、要不要跳著更新,都能自己決定。缺點是必須自己處理執行緒切換(如範例中的 runOnUiThread),並在 Activity 銷毀時記得 cancel 掉 Timer,否則會造成記憶體洩漏。實務上這類固定週期的計時任務,改用 Handler 的 postDelayed 或 ScheduledExecutorService 往往會比 Timer 更合適。

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