我正在嘗試使用timertask更新我的數字時鐘。我創建了一個名爲updateClock()的函數,它將小時和分鐘設置爲當前時間,但我無法定期運行它。從我在其他答案中看到的其中一個最好的選擇是使用timertask,但是我還沒有能夠在Android活動中發現任何在線工作的例子。使用timertask每X秒更新一次時鐘?
這是我到目前爲止已經寫的:
public class MainActivity extends Activity {
TextView hours;
TextView minutes;
Calendar c;
int cur_hours;
int cur_minutes;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.clock_home);
hours = (TextView) findViewById(R.id.hours);
minutes = (TextView) findViewById(R.id.minutes);
updateClock();
}
public void updateClock() {
c = Calendar.getInstance();
hours.setText("" + c.get(Calendar.HOUR));
minutes.setText("" + c.get(Calendar.MINUTE));
}
public static void init() throws Exception {
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
updateClock(); // ERROR
}
}, 0, 1 * 5000);
}
}
我怎樣才能使它發揮作用?
Android已經在['Chronometer'(http://developer.android.com/reference/android/widget/Chronometer.html)如果你有興趣。 – Sam