Android:用定時器 timer 重新整理介面
阿新 • • 發佈:2019-02-16
Posted by: tigerz on March 6, 2010
在 Android 平臺上,介面元素不能在定時器的響應函式裡重新整理。
以下這段程式碼中,mButton 的文字並不變化。
public
private Button mButton;
private Timer mTimer;
private TimerTask mTimerTask;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.main);
mButton = (Button) findViewById(R.id.Button01);
mTimer = new Timer();
mTimerTask = new TimerTask() {
@Override
public void run() {
Log.d(, "timer");
Calendar cal = Calendar.getInstance();
mButton.setText(cal.toString());
}
};
mTimer.schedule(mTimerTask, 1000 , 1000);
}
}
在 Android 平臺上,UI 單元必須在 Activity 的 context 裡重新整理。 為了達到想要的效果,可以使用 Message Handler。在定時器響應函式裡傳送條訊息,在 Activity 裡響應訊息並更新文字。
public
protected static final int UPDATE_TEXT = 0;
private Button mButton;
private Timer mTimer;
private TimerTask mTimerTask;
private Handler mHandler;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mButton = (Button) findViewById(R.id.Button01);
mTimer = new Timer();
mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case UPDATE_TEXT:
Calendar cal = Calendar.getInstance();
mButton.setText(cal.toString());
break;
}
}
};
mTimerTask = new TimerTask() {
@Override
public void run() {
Log.d(, "timer");
mHandler.sendEmptyMessage(UPDATE_TEXT);
/*
// It doesn't work updating the UI inside a timer.
Calendar cal = Calendar.getInstance();
mButton.setText(cal.toString());
*/
}
};
mTimer.schedule(mTimerTask, 1000, 1000);
}
}