我想结束从 Android 设备到 Web 服务器的 HTTP 请求,并定期(每分钟一次)检查数据库的特定数据。我无法为此实现计时器。
谢谢
public class MyActivity extends Activity {
Timer t ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t = new Timer();
t.schedule(new TimerTask() {
public void run() {
//Your code will be here
}
}, 1000);
}
}
尝试AlarmManager
运行Service
。我不建议您每分钟发送请求,除非它仅在用户手动触发此操作时发生。
TimerTask doAsynchronousTask;
final Handler handler = new Handler();
Timer timer = new Timer();
doAsynchronousTask = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
if(isOnline){// check net connection
//what u want to do....
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 10000);// execute in every 10 s
最简单的方法是循环处理程序:
private Handler iSender = new Handler() {
@Override
public void handleMessage(final Message msg) {
//Do your code here
iSender.sendEmptyMessageDelayed(0, 60*1000);
}
};
要开始循环,请调用以下语句:
iSender.sendEmptyMessage(0);