[当应用程序运行时]定期执行操作的最佳方式 - 处理程序?
我正在尝试定期执行一项操作。我想每隔 3 秒创建一个类的新实例。最好使用处理程序还是线程来实现此目的?有没有一种更简单、有点愚蠢的方法我可以尝试?我真的不擅长使用线程 - 我想学习,但更重要的是在担心良好的编程实践之前让它发挥作用。
new Thread(){
public void run(){
//makes sure the player still has 3 lives left
while(game == false){
uiCallback.sendEmptyMessage(0);
try {
Thread.sleep(2000); // wait two seconds before drawing the next flower
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //sleep for 2 seconds
}
}
}.start();
I'm trying to perform an action periodically. I want to create a new instance of a class after, say, ever 3 seconds. Would it be best to implement this by using a Handler or a Thread? Is there an easier, sort of dopey way I could try? I'm really not good at using threads - I want to learn, but it is more important that I get this to function before worrying about good programming practices.
new Thread(){
public void run(){
//makes sure the player still has 3 lives left
while(game == false){
uiCallback.sendEmptyMessage(0);
try {
Thread.sleep(2000); // wait two seconds before drawing the next flower
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //sleep for 2 seconds
}
}
}.start();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我正在我的 Android 应用程序中做类似的事情;我每 10 秒更新一次界面中的一些数据。有很多方法可以做到这一点,但我选择使用
Handler
因为它实现起来非常简单:正如您可能知道的,您不能在 UI 线程中运行这样的周期性函数,因为它会阻塞用户界面。这将创建一个新的
Thread
,该线程在完成时向 UI 发送一条消息,因此您可以使用周期性函数执行的任何操作的新结果来更新 UI。如果您不需要使用此周期函数的结果更新 UI,则可以简单地忽略代码示例的后半部分,而只需生成一个新的
Thread
,如图所示。但请注意:如果您要修改这个新Thread
和 UI 共享的变量,如果不同步,就会遇到问题。一般来说,线程不是您想要忽略“良好编程实践”的领域,因为您会遇到奇怪的、不可预测的错误,并且您会咒骂您的程序。-tjw
I'm doing something similar in my android app; I update some data in my interface every 10 seconds. There are many ways to do this, but I chose to use a
Handler
because it's very simple to implement:As you may know, you cannot run periodic functions like this in the UI thread, because it will block the UI. This creates a new
Thread
that sends a message to the UI when it is done, so you can update your UI with the new results of whatever your periodic function does.If you do not need to update the UI with the results of this periodic function, you can simply ignore the second half of my code example, and just spawn a new
Thread
as shown. Beware, however: if you are modifying variables shared by this newThread
and the UI, you are going to run into problems if you don't synchronize. In general, threading is not an area where you want to ignore "good programming practices" because you'll get strange, non-predictable errors and you'll be cursing your program.-tjw
最简单的事情是在
View
(例如,一个小部件)上使用postDelayed()
来调度一个可以工作的Runnable
,然后重新调度自己。The simplest thing is to use
postDelayed()
on aView
(e.g., a widget) to schedule aRunnable
that does work, then reschedules itself.