Reputation: 5881
I am working on a app that has to work in the background and send location updates to the server.
The code is pretty simple and normaly works. There is a service that has a Timer that sends updates to the server every 15 seconds and it also implements the LocationListener Interface.
I dont think giving all the code would be useful, here is how I set up the class:
@Override
public void onCreate() {
super.onCreate();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER , 5000, 10.0f, this);
locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER , 5000, 10.0f, this);
//Ping Task sends updates to the Server
Ping_Timer.scheduleAtFixedRate( new Ping_Task(), 5000, Ping_Task.TIME_GET_JOBS*1000 );
}
In practice I have some problems with my code. Services should work in the background, even if the Service stoppes there is a GCM system in place to restart the service in the background.
Even with these protections I still have the problems, sometimes the app does not update the location anymore, even if it is clear that the service is still running. On the Google Maps App I can see that the Location is correct there, but not in my app. How can this be, why do I not get the 'onLocationChanged' event anymore.
Thanks for your help.
Upvotes: 0
Views: 269
Reputation: 1997
First, I am not sure about Service
life cycle. But I used the code below in onStart()
method of the Service
. This method is called after calling startService(Intent)
method on Context
. I guess, you can do this in onCreate()
method.
Implement a location listener:
private final static LocationListener listener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
//locationHandler will be created below.
Message.obtain(locationHandler, 0, location.getLatitude() + ", " + location.getLongitude()).sendToTarget();
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
Give your listener to the method instead this
locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 5000, 10.0f, listener);
locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 5000, 10.0f, listener);
Implement a handler for this listener in your onStart()
method in Service
.
Handler locationHandler = new Handler() {
@Override
public void handleMessage(android.os.Message msg) {
String location = (String) msg.obj;
//do what you wanna do with this location
}
}
This is how I did.
Upvotes: 2