我在我的服务中使用 Timer 和 TimerTask,我正在安排 GPS 使用此方法定期检查 @Service - onCreate()
scheduleAllGPST.scheduleAtFixedRate(new AllGPSTimer(), 0,
everyInterval);
我的服务类中的代码片段:
//class inside service class
class AllGPSTimer extends TimerTask {
public void run() {
if (!canGetLocation) stopLocationRequest();
else requestLocation();
}
}
// Service class method
public void requestLocation() {
try {
locListener = new mylocationlistener();
locationManager.requestLocationUpdates(provider, 0, 0, locListener);// Error happens at this line
}
catch (Exception e) {
e.printStackTrace();
}
}
public void stopLocationRequest() {
try {
locationManager.removeUpdates(locListener);// And also it happens at this line
}
catch (Exception e) {
e.printStackTrace();
}
}
我收到此错误:
Error :
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:121)
at android.location.LocationManager$ListenerTransport$1.<init>(LocationManager.java:139)
at android.location.LocationManager$ListenerTransport.<init>(LocationManager.java:137)
at android.location.LocationManager._requestLocationUpdates(LocationManager.java:708)
at android.location.LocationManager.requestLocationUpdates(LocationManager.java:630)
at com.mobile.sales.GPSService.requestLocation(GPSService.java:146)
at com.mobile.sales.GPSService$AllGPSTimer.run(GPSService.java:140)
at java.util.Timer$TimerImpl.run(Timer.java:289)
从错误中,我猜这个 requestLocationUpdates() 和 removeUpdates() 只能从 Service 类的主线程中使用,而不是从主线程的衍生线程中使用。我猜对了吗?
那么Service类的Activity类中是否有类似runOnUiThread(runnable)的方法?
请任何人帮助我处理位置 API 方法和计时器任务的衍生线程?如果我猜错了,也请告诉我。
谢谢!