GPS 无法在 TimerTask 内运行
我正在尝试编写一个 Android 应用程序,以固定的时间间隔(例如每 1 分钟)获取 GPS 信号。由于 requestLocationUpdate 函数没有完全实现它,我尝试使用任务来完成它。
public class getGPS extends TimerTask{
public void run(){
System.out.println("Running a GPS task");
locHandler = new locationUpdateHandler();
myManager.requestLocationUpdates(provider, 60000, 0, locHandler);
}
}
public void LoadCoords(){
Timer timer = new Timer();
timer.scheduleAtFixedRate(new getGPS(), 0, 60000);
}
然而,从我所见,如果我将 requestLocationUpdates 放在 LoadCoords() 中,它会运行得很好,但如果我将它放在 TimerTask 中,则不会运行(即任务栏上没有绿色图标来表明 GPS 正在寻找位置)使固定)。
任何人都可以建议一种替代方法或伪代码,或者纠正我的错误(如果有)吗?先感谢您。
I am trying to write an android app that acquires a GPS signal at a fix time interval, for example every 1 minute. Since the requestLocationUpdate function does not exactly implement that, I tried to use task to accomplished it.
public class getGPS extends TimerTask{
public void run(){
System.out.println("Running a GPS task");
locHandler = new locationUpdateHandler();
myManager.requestLocationUpdates(provider, 60000, 0, locHandler);
}
}
public void LoadCoords(){
Timer timer = new Timer();
timer.scheduleAtFixedRate(new getGPS(), 0, 60000);
}
However, from what I've seen, requestLocationUpdates would run fine if I put it inside LoadCoords(), but would not run if I put it inside the TimerTask (ie no green icon on the task bar to show that GPS is looking for a fix).
Can anyone please suggest an alternative approach or pseudo-code, or correct my mistake if there is one ? Thank you in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
作为doc 说:调用线程必须是 Looper 线程,例如调用 Activity 的主线程。换句话说,您应该从主 UI 应用线程调用
myManager.requestLocationUpdates(provider, 60000, 0, locHandler);
。在您的情况下,这在 TimerTask 中不起作用,因为 TimerTasks 是由 Timer 在单独的线程上执行的。查看无痛线程文章来了解您的情况最佳拟合解决方案。
As the doc says: The calling thread must be a Looper thread such as the main thread of the calling Activity. In other words you should call
myManager.requestLocationUpdates(provider, 60000, 0, locHandler);
from a main UI app thread. In your case that does not work from theTimerTask
, because TimerTasks are being executed byTimer
on a separate thread.Check the Painless Threading article to find out your best fitting solution.