Java 是否使用timertask每X秒更新一次时钟?
我正在尝试使用timertask更新我的数字时钟。我创建了一个名为UpdateLock()的函数,它将小时和分钟设置为当前时间,但我无法让它定期运行。从我在其他答案中读到的内容来看,最好的选择之一是使用timertask,但是我还没有找到任何在Android活动中在线工作的例子 这是我到目前为止写的:Java 是否使用timertask每X秒更新一次时钟?,java,android,Java,Android,我正在尝试使用timertask更新我的数字时钟。我创建了一个名为UpdateLock()的函数,它将小时和分钟设置为当前时间,但我无法让它定期运行。从我在其他答案中读到的内容来看,最好的选择之一是使用timertask,但是我还没有找到任何在Android活动中在线工作的例子 这是我到目前为止写的: public class MainActivity extends Activity { TextView hours; TextView minutes; Calenda
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);
}
}
如何使其工作?用于从计时器线程更新Ui
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
MainActivity.this.runOnUiThread (new Runnable() {
public void run() {
updateClock(); // call UI update method here
}
}));
}
}, 0, 1 * 5000);
}
或者,定期将Runnable发布到UI线程的处理程序。此外,暂停并继续执行任务以节省电池电量
public class MyActivity extends Activity {
private final Handler mHandler = new Handler();
private final Timer mTimer = new Timer();
@Override
protected void onResume() {
super.onResume();
mTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
mHandler.post(new Runnable() {
@Override
public void run() {
//---update UI---
}
});
}
},0,5000);
}
@Override
protected void onPause() {
super.onPause();
mTimer.cancel();
}
}
如果您每分钟都需要更新,您还可以收听
ACTION\u TIME\u TICK
广播事件
private boolean timeReceiverAttached;
private final BroadcastReceiver timeReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
updateClock();
}
};
private Handler handler = new Handler();
@Override
protected void onResume() {
super.onResume();
updateClock();
if (!timeReceiverAttached) {
timeReceiverAttached = true;
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_TIME_TICK);
filter.addAction(Intent.ACTION_TIME_CHANGED);
filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
registerReceiver(timeReceiver, filter, null, handler);
}
}
@Override
protected void onPause() {
super.onPause();
if (timeReceiverAttached) {
unregisterReceiver(timeReceiver);
timeReceiverAttached = false;
}
}
如果你感兴趣的话,Android有这个功能。