I am using Timer and TimerTask in my Service and I am scheduling GPS to check periodically using this method @ Service - onCreate()
scheduleAllGPST.scheduleAtFixedRate(new AllGPSTimer(), 0,
everyInterval);
Code Snippet From my Service Class:
//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();
}
}
I am getting this error:
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)
From the Error, I am guessing this requestLocationUpdates() and removeUpdates() can only be used from the Main thread of the Service class, not from the spawned thread of the main thread. Am I guessing it correctly?
So is there any method like runOnUiThread(runnable) in Activity class for the Service class?
Kindly any one help with I should handle location API methods and the spawned thread of the timer task? Also let me know if I am guessing it wrong .
Thank you!