我正在尝试定期执行某项操作。我想创建一个类的新实例,比如说,持续3秒。最好通过使用Handler或Thread来实现它吗?我可以尝试一种更容易,更笨拙的方式吗?我真的不擅长使用线程 - 我想学习,但更重要的是,我要在完成编程实践之前让它运行起来。
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();
答案 0 :(得分:13)
我在我的Android应用程序中做了类似的事情;我每隔10秒更新一次界面中的一些数据。有很多方法可以做到这一点,但我选择使用Handler
,因为它实现起来非常简单:
Thread timer = new Thread() {
public void run () {
for (;;) {
// do stuff in a separate thread
uiCallback.sendEmptyMessage(0);
Thread.sleep(3000); // sleep for 3 seconds
}
}
});
timer.start();
...
private Handler uiCallback = new Handler () {
public void handleMessage (Message msg) {
// do stuff with UI
}
};
如您所知,您无法在UI线程中运行此类周期性函数,因为它会阻止UI。这会创建一个新的Thread
,在完成后向UI发送消息,因此您可以使用您的定期函数所做的新结果更新UI。
如果您不需要使用此周期函数的结果更新UI,则可以忽略代码示例的后半部分,并生成一个新的Thread
,如图所示。但要注意:如果要修改此新Thread
和UI共享的变量,如果不进行同步,则会遇到问题。一般来说,线程不是一个你想忽略“良好的编程实践”的领域,因为你会得到奇怪的,不可预测的错误,你会诅咒你的程序。
-tjw
答案 1 :(得分:9)
最简单的方法是在postDelayed()
(例如小工具)上使用View
来安排有效的Runnable
,然后重新安排自己。
答案 2 :(得分:0)
// We need to use this Handler package
import android.os.Handler;
// Create the Handler object (on the main thread by default)
Handler handler = new Handler();
// Define the code block to be executed
private Runnable runnableCode = new Runnable() {
@Override
public void run() {
// Do something here on the main thread
Log.d("Handlers", "Called on main thread");
// Repeat this the same runnable code block again another 2 secs
// 'this' is referencing the Runnable object
handler.postDelayed(this, 2000);
}
};
// Start the initial runnable task by posting through the handler
handler.post(runnableCode);