2010年12月18日 星期六

計時器(Timer)

1. 由於若不是Main Thread則無法去變更畫面的Widget內容,需透過android.os.Handler來達到此效果。

2. MainActivity.java

01.package org.me.android_timer;
02.import android.app.Activity;
03.import android.os.Bundle;
04.import android.os.Handler;
05.import android.widget.TextView;
06. 
07.public class MainActivity extends Activity {
08.    private Long startTime;
09.    private Handler handler = new Handler();
10. 
11.    @Override
12.    public void onCreate(Bundle savedInstanceState) {
13.        super.onCreate(savedInstanceState);
14.        setContentView(R.layout.main);
15.        //取得目前時間
16.        startTime = System.currentTimeMillis();
17.        //設定定時要執行的方法
18.        handler.removeCallbacks(updateTimer);
19.        //設定Delay的時間
20.        handler.postDelayed(updateTimer, 1000);
21.    }
22. 
23.    //固定要執行的方法
24.    private Runnable updateTimer = new Runnable() {
25.        public void run() {
26.            final TextView time = (TextView) findViewById(R.id.timer);
27.            Long spentTime = System.currentTimeMillis() - startTime;
28.            //計算目前已過分鐘數
29.            Long minius = (spentTime/1000)/60;
30.            //計算目前已過秒數
31.            Long seconds = (spentTime/1000) % 60;
32.            time.setText(minius+":"+seconds);
33.            handler.postDelayed(this, 1000);
34.        }
35.    };
36.}


3. main.xml(Layout)
01.<?xml version="1.0" encoding="utf-8"?>
02.<AbsoluteLayout
03.    android:id="@+id/widget0"
04.    android:layout_width="fill_parent"
05.    android:layout_height="fill_parent"
07.    >
08.    <TextView
09.        android:id="@+id/timer"
10.        android:layout_width="wrap_content"
11.        android:layout_height="wrap_content"
12.        android:text="0:0"
13.        android:textSize="70sp"
14.        android:layout_x="90px"
15.        android:layout_y="160px"
16.        >
17.    </TextView>
18.</AbsoluteLayout>


4. 執行之後的畫面。

沒有留言:

張貼留言