我有一个Android应用程序,它有一个运行任务的计时器:
time2.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
sendSamples();
}
}, sampling_interval, sending_interval);
让我们说sampling_interval是2000而sending_interval是4000.
因此,在此应用程序中,我将一些读取值从传感器发送到服务器。但我想在10000(10秒)之后停止发送。
我该怎么办?
答案 0 :(得分:9)
试
time2.scheduleAtFixedRate(new TimerTask() {
long t0 = System.currentTimeMillis();
@Override
public void run() {
if (System.currentTimeMillis() - t0 > 10 * 1000) {
cancel();
} else {
sendSamples();
}
}
...
答案 1 :(得分:0)
检查此代码:
private final static int DELAY = 10000;
private final Handler handler = new Handler();
private final Timer timer = new Timer();
private final TimerTask task = new TimerTask() {
private int counter = 0;
public void run() {
handler.post(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this, "test", Toast.LENGTH_SHORT).show();
}
});
if(++counter == 4) {
timer.cancel();
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timer.schedule(task, DELAY, DELAY);
}