標題:
Android App - 計時器
[打印本頁]
作者:
admin
時間:
2013-8-24 17:09
標題:
Android App - 計時器
以下例子TextView1 會顯示數字, 由0 開始每秒加一
Timer t = new Timer();
int time=0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mContext = this;
t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(String.valueOf(time));
time += 1;
}
});
//Called each time when 1000 milliseconds (1 second) (the period parameter)
}
},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
1000);
}
複製代碼
作者:
admin
時間:
2013-8-24 17:38
或者把上面程式以 method 處理
Timer t = new Timer();
int time=0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mContext = this;
t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() { TimerMethod();
}
}, //Set how long before to start calling the TimerTask (in milliseconds)
0, //Set the amount of time between each execution (in milliseconds)
1000);
}
private void TimerMethod()
{
//This method is called directly by the timer
//and runs in the same thread as the timer.
//We call the method that will work with the UI
//through the runOnUiThread method.
this.runOnUiThread(Timer_Tick);
}
private Runnable Timer_Tick = new Runnable() {
public void run() {
//This method runs in the same thread as the UI.
TextView tv = (TextView) findViewById(R.id.textView2);
tv.setText(String.valueOf(time));
time += 1;
}
};
複製代碼
作者:
admin
時間:
2013-9-9 20:50
採用Timer 其中一個問題是不能隨時 enable 及disable timer, 我們可以採用 handle 做計時器
歡迎光臨 How2Do (http://forum.how2do.com.hk/)
Powered by Discuz! 7.2