编辑:
这并不是关于精度问题的讨论。从下面的代码和日志可以看出,我请求睡眠1秒钟,但结果却接近200秒,有时候甚至会跳到600秒,这不能是精度问题。
之前我在使用 handlerthread,有时候提交给 handler 的作业就是无法按时启动,为了获取更多细节,我将它改成了基本的 Thread,结果发现 Thread.sleep() 是问题所在,但我不知道该如何解决,可能的原因是什么呢?
hGpsThread = new Thread(mGpsWorker);
hGpsThread.start();
private final Runnable mGpsWorker = new Runnable() {
@Override
public void run() {
long lastGpsRequestTime = 0;
l.Write("GPS thread started.");
while (isRunning) {
l.Write("GPS thread loop start.");
try {
long currentTimeMillis = System.currentTimeMillis();
if (currentTimeMillis >= lastGpsRequestTime + gpsUpdateInterval) {
l.Write("Requesting location update");
gpslib.getLocation();
lastGpsRequestTime = currentTimeMillis;
}
l.Write("GPS thread before sleep");
Thread.sleep(1000);
l.Write("GPS thread after sleep");
} catch (InterruptedException e) {
}
l.Write("GPS thread loop end.");
}
l.Write("GPS thread ended.");
}
};
注意:getLocation()调用requestLocationUpdates,使用来自另一个线程的looper,因此位置更新不应影响此线程,据我所知。
getLocation()还创建了一个计时器并安排了超时,这可能是问题吗?据我所知,这不应该是问题。
这是日志记录:(这仅偶尔发生,例如机会接近0.5%)
Wed Jul 10 11:45:46 AEST 2013 GPS thread loop start.
Wed Jul 10 11:45:46 AEST 2013 GPS thread before sleep
Wed Jul 10 11:49:04 AEST 2013 GPS thread after sleep
Wed Jul 10 11:49:04 AEST 2013 GPS thread loop end.
感谢
测试环境为:HTC Aria,Android 2.2 并且看起来只有在电池模式下运行时才会发生,但我的应用程序在充电状态下不会有任何不同。
getLocation()
时,这种情况是否会发生?看来另一个线程在这个进入sleep
后没有放弃 CPU。 - Aert