I have created a GPS service which reads location updates on a regular interval. Earlier there was an issue that GPS was going in sleep mode after some time and no location updates were giver thereafter.
Now I have changed my code to unregister and register GPS location updates on a regular interval. This solves my problem of GPS going in sleep mode but a new issue is created. That is
My service is terminated after some time. I am not able to check the reason for this. Please Help.
Here are some code snipplets
@Override
public void onCreate() {
super.onCreate();
timer.schedule(checkLocationListener, new Date(), 1000 * 60 * 15);
}
private TimerTask checkLocationListener = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
lm.removeUpdates(LocationService.this);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, CommonConstants.GPS_POLL,
CommonConstants.GPS_MIN_DIST, LocationService.this);
}
});
}
};
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(LocationService.class.getSimpleName(), "Start");
valueMap.put(CommonConstants.STATUS, CommonConstants.STATUS_DROP);
trackMe();
new Thread() {
public void run() {
while (true) {
try {
String url = DeviceConfig.getMessage();
if (url == null) {
Thread.sleep(60000);
continue;
}
HttpRequester.getServerResponse(url, null);
DeviceConfig.addValue(CommonConstants.SERVER_UPD, "" + System.currentTimeMillis());
DeviceConfig.removeMessage();
} catch (Exception e) {
Log.e(LocationService.class.getSimpleName(), "Error", e);
}
}
}
}.start();
return (START_NOT_STICKY);
}
private void trackMe() {
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, CommonConstants.GPS_POLL, CommonConstants.GPS_MIN_DIST,
this);
DeviceConfig.addValue(CommonConstants.GPS_STATE, lm.isProviderEnabled(LocationManager.GPS_PROVIDER)
? CommonConstants.ON : CommonConstants.OFF);
}
You wont need to register/unregister location update listener again and again, It seems your service stopped, so start your service in sticky mode, in that way, service can be stopped explicitly only.