定时java循环

时间:2011-08-10 18:40:16

标签: java android loops time

我是新的机器人,我很感激一些帮助。我有这段代码:

        dateatm = (TextView) findViewById(R.id.date);
        timeatm = (TextView) findViewById(R.id.tvTime);
        Calendar currentDate = Calendar.getInstance();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MMM/dd");
        SimpleDateFormat värk = new SimpleDateFormat("HH:mm:ss");
        String dateNow = formatter.format(currentDate.getTime());
        String timeNow = värk.format(currentDate.getTime());
        dateatm.setText(dateNow);
        timeatm.setText(timeNow);

正如您所看到的,我正在获取日期和时间。我想要的是,将有1秒循环,所以在每1秒之后,它将一次又一次地更新日期和时间到新的基本上获得时钟。我很新人,所以所有的帮助都很高兴如何完成这项工作。如果你带上一些确切的例子,我会很感激,因为它让它更容易理解,而不仅仅是“哦,使用那个,那个。谢谢!”。

感谢您的帮助和时间, 精灵:))


答案1的错误:

08-10 18:55:41.335: ERROR/AndroidRuntime(886): FATAL EXCEPTION: Timer-0
08-10 18:55:41.335: ERROR/AndroidRuntime(886): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
08-10 18:55:41.335: ERROR/AndroidRuntime(886):     at android.view.ViewRoot.checkThread(ViewRoot.java:2932)
08-10 18:55:41.335: ERROR/AndroidRuntime(886):     at android.view.ViewRoot.invalidateChild(ViewRoot.java:642)
08-10 18:55:41.335: ERROR/AndroidRuntime(886):     at android.view.ViewRoot.invalidateChildInParent(ViewRoot.java:668)
08-10 18:55:41.335: ERROR/AndroidRuntime(886):     at android.view.ViewGroup.invalidateChild(ViewGroup.java:2511)
08-10 18:55:41.335: ERROR/AndroidRuntime(886):     at android.view.View.invalidate(View.java:5279)
08-10 18:55:41.335: ERROR/AndroidRuntime(886):     at android.widget.TextView.checkForRelayout(TextView.java:5507)
08-10 18:55:41.335: ERROR/AndroidRuntime(886):     at android.widget.TextView.setText(TextView.java:2724)
08-10 18:55:41.335: ERROR/AndroidRuntime(886):     at android.widget.TextView.setText(TextView.java:2592)
08-10 18:55:41.335: ERROR/AndroidRuntime(886):     at android.widget.TextView.setText(TextView.java:2567)
08-10 18:55:41.335: ERROR/AndroidRuntime(886):     at viimane.voimalus.MainStuff$1.run(MainStuff.java:55)
08-10 18:55:41.335: ERROR/AndroidRuntime(886):     at java.util.Timer$TimerImpl.run(Timer.java:284)

1 个答案:

答案 0 :(得分:5)

我刚刚在我的项目中解决了这个问题(以特定间隔执行代码):)

编辑以反映更新的答案:

protected static final int REFRESH = 0;
private Timer timer;
private TimerTask refresher;

private Handler handler = new Handler() {
    public void handleMessage(Message msg) {
        switch (msg.what) {
        case REFRESH:
            /* your code here */
            break;
        default:
            break;
        }
    }
};

// onCreate或类似的初始化代码:

timer = new Timer();    
refresher = new TimerTask() {
    public void run() {
        ActivityMain.this.sendEmptyMessage(REFRESH);
    };
};
// first event immediately,  following after 1 seconds each
timer.scheduleAtFixedRate(refresher, 0, 1000);