我想在 android 中每秒执行一些代码,但我想在一个线程(主线程)中执行。到目前为止我有这个:
locationTimer = new Timer("locationTimer", false);
locationTimer.schedule(new LocationCheckerTask(this), 0, 1000);
public class LocationCheckerTask extends TimerTask {
private GeoWatcher watcher;
public LocationCheckerTask(Context context) {
watcher = new GeoWatcher(context);
}
@Override
public void run() {
// funky stuff
}
}
不幸的是,Timer
类在另一个线程上运行它的任务。
为什么我想在一个线程中执行此操作?
run()
方法中的代码将执行得非常快,所以我认为我不需要另一个线程。我想做的是根据每秒计算的条件在 run()
方法中构造单独的线程。因此,我不想让子线程构造另一个线程,而是想在主线程上执行此操作。
最佳答案
您可以使用 Handler 执行此操作
public class Job implements Runnable{
private Handler handler;
public Job () {
handler = new Handler(Looper.getMainLooper());
loop();
}
@Override
public void run() {
// funky stuff
loop();
}
private void loop() {
handler.postDelayed(this, 1000);
}
}
关于java - 每秒执行一次方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20785332/