gpt4 book ai didi

java - 定时java循环

转载 作者:搜寻专家 更新时间:2023-11-01 07:38:38 25 4
gpt4 key购买 nike

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

        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 秒后,它会一次又一次地更新日期和时间到较新的日期和时间以获得基本时钟。我是新手,所以感谢所有帮助如何完成这项工作。如果您能提供确切的示例,我将不胜感激,因为它使它更容易理解,而不仅仅是“哦,使用那个那个那个。谢谢!”。

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


答案 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)

最佳答案

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

编辑以反射(reflect)更新的答案:

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);

关于java - 定时java循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7015994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com