我需要定期执行一些代码(连接到服务器并每分钟从 MySQL 数据库中提取数据)。为此,我有一个 Sync 类:
public class Sync {
static private Handler handler = new Handler();
Runnable task;
public Sync(Runnable task, long time) {
this.task = task;
handler.removeCallbacks(task);
handler.postDelayed(task, time);
}
}
在我的活动中,我有:
public void onCreate(Bundle savedInstanceState) {
...
Sync sync = new Sync(call,60*1000);
...
}
final private Runnable call = new Runnable() {
public void run() {
//This is where my sync code will be, but for testing purposes I only have a Log statement
Log.v("test","this will run every minute");
}
};
我已经尝试过用更短的时间进行测试,但它只运行一次。当它第一次记录消息时,它也是最后一次。有谁看到我在这里做错了什么?谢谢!