我想每5秒鐘更新一次屏幕上的文本,就創建了一個 timer 計時器來實現。但是只有第一次更新了,以後再沒更新。是不是我需要刷新視圖或者使用別的方法?
public class HomeActivity extends Activity implements OnClickListener {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textTitle = (TextView) findViewById(R.id.textTitle);
textArtist = (TextView) findViewById(R.id.textArtist);
timedMeta();
}
static void timedMeta()
{
timer.scheduleAtFixedRate(
new TimerTask() {
public void run() {
try{
textTitle.setText(title);
textArtist.setText(artist);
}
Thread.sleep(UPDATE_INTERVAL);
catch (Exception e)
{
},
DELAY_INTERVAL,
UPDATE_INTERVAL);
}
}
)
}
要使用一個 Handler.
private static final int WHAT = 1;
private static final int TIME_TO_WAIT = 5000;
Handler regularHandler = new Handler(new Handler.Callback() {
public boolean handleMessage(Message msg) {
// Do stuff
regularHandler.sendEmptyMessageDelayed(msg.what, TIME_TO_WAIT);
return true;
}
});
regularHandler.sendEmptyMessageDelayed(WHAT, TIME_TO_WAIT);
onPause()
regularHandler.removeMessages(WHAT)