1. 程式人生 > >Android使用Handler+postDelayed實現簡單計時器

Android使用Handler+postDelayed實現簡單計時器

我們在開發中會時常用到計時器,比如計算我們的APP工作的時長,下面介紹兩種實現方案。

一、使用Handler+postDelayed實現計時器

先看效果圖:


實現的程式碼:

public class MainActivity extends AppCompatActivity {

    protected Button btnStart;
    protected Button btnEnd;
    static TextView tvWorkTime;
    static Handler timeHandler = new Handler();
    static Date beginDate = null;

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

    private void initView() {
        btnStart = (Button) findViewById(R.id.btn_start);
        btnEnd = (Button) findViewById(R.id.btn_end);
        tvWorkTime = (TextView) findViewById(R.id.tv_work_time);
    }

    public void start(View view) {
        btnStart.setVisibility(View.GONE);
        btnEnd.setVisibility(View.VISIBLE);
        beginDate = new Date();
        timeHandler.postDelayed(runnable, 1000);
    }

    public void end(View view) {
        btnStart.setVisibility(View.VISIBLE);
        btnEnd.setVisibility(View.GONE);
        timeHandler.removeCallbacks(runnable);
    }

    static Runnable runnable = new Runnable() {
        @Override
        public void run() {
            TimeUtils(beginDate, new Date());
            timeHandler.postDelayed(this, 1000);
        }
    };

    public static void TimeUtils(Date beginDate, Date endDate){
        SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long between = 0;
        Date begin = null;
        Date end = null;
        try {
            begin = dfs.parse(datetimeToString(beginDate));
            end = dfs.parse(datetimeToString(endDate));
            between = (end.getTime() - begin.getTime());// 得到兩者的毫秒數
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long day = between / (24 * 60 * 60 * 1000);
        long hour = (between / (60 * 60 * 1000) - day * 24);
        long min = ((between / (60 * 1000)) - day * 24 * 60 - hour * 60);
        long s = (between / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        tvWorkTime.setText("工作時長:" + hour + " : " + min + " : " + s);
    }

    public static String datetimeToString(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }
}
佈局檔案:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/btn_start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="30dp"
        android:layout_marginTop="20dp"
        android:background="@drawable/button"
        android:onClick="start"
        android:text="開始計時"
        android:textSize="24sp"/>

    <Button
        android:id="@+id/btn_end"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="30dp"
        android:layout_marginTop="20dp"
        android:background="@drawable/button"
        android:onClick="end"
        android:visibility="gone"
        android:text="結束計時"
        android:textSize="24sp"/>

    <TextView
        android:id="@+id/tv_work_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="工作時長:0 : 0 : 0"
        android:layout_marginTop="30dp"
        android:layout_marginLeft="20dp"
        android:textSize="20sp"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="12dp"/>
</LinearLayout>

按鈕樣式:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="false">
        <shape android:shape="rectangle" >
            <solid android:color="#0FFFFF" />
            <corners android:radius="15dip" />
            <padding android:bottom="10dp" android:left="10dp" android:right="10dp" android:top="10dp" />
        </shape>
    </item>
    <item android:state_pressed="true">
        <shape android:shape="rectangle">
            <solid android:color="#FFFF0F" />
            <corners android:radius="15dip" />
        </shape>
    </item>
</selector>

二、使用Chronometer實現計時器

public class Main2Activity extends AppCompatActivity {

    protected Chronometer timer;

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

    private void initView() {
        timer = (Chronometer) findViewById(R.id.timer);
    }
    public void start(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 stop(View view){
        timer.stop();
    }
}

佈局檔案:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="start"
        android:onClick="start"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="stop"
        android:onClick="stop"/>
    <Chronometer
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:format="00:00:00"
        android:textSize="20sp"
        android:id="@+id/timer"/>
</LinearLayout>