我想做那样的事情:
@Override
protected String doInBackground(Object... params) {
int i = 0;
int max = Integer.MAX_VALUE;
GPSTracker gps = new GPSTracker(context);
do
{
//Something
} while(10 seconds);
return null;
}
如何计算一段时间的计数时间。我想在10秒钟内做到这一点。
答案 0 :(得分:2)
要延迟执行,您可以sleep
一个帖子:
Thread.sleep(timeInMills);
这一行可能抛出一个线程异常,它永远不应该在主UI线程上执行,因为它会导致应用停止与Android的通信,导致ANR
。
要在单个活动的后台运行流程,您应该生成一个新的Thread
。
new Thread(){
public void run(){
//Process Stuff
}
}.start();
如果您希望在应用程序的整个生命周期中运行此部分代码,包括在用户隐藏它时,您应该考虑为长期任务运行服务。
答案 1 :(得分:2)
如果您想要定期运行任务,请使用Timer#scheduleAtFixedRate
。
答案 2 :(得分:0)
的便捷替代方案
Thread.sleep(timeInMillis)
是
TimeUnit.SECONDS.sleep(10)
然后单位更明确,更容易推理。
请注意,这两个方法都会抛出InterruptedException,您必须处理它。您可以详细了解here。如果像往常一样,你不想使用中断,并且你不希望你的代码混乱使用try / catch块,那么Google Guava's Uninterruptibles可以很方便:
Uninterruptibles.sleepUninterruptibly(10, TimeUnit.SECONDS);
答案 3 :(得分:0)
你可以使用Thread.sleep(); (不是很干净)。
最好使用Handler来执行此操作。
例如:
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
// You code here
}
}, 775); // Time in millis
答案 4 :(得分:0)
我做到了:
long start = System.currentTimeMillis();
long end = start + 60*1000; // 60 seconds * 1000 ms/sec
while (System.currentTimeMillis() < end)
{
// run
}
感谢您的所有答案。