I am trying to create an Android application that continuously logs device location data in realtime while the device screen is off. My code works correctly with Android 6.0 and
LocationServices.FusedLocationApi is deprecated.
I just refactored my App as follows. Hope it helps:
This is what I am calling in the onCreate-Method of my Service:
public void start(Context ctx) {
FusedLocationProviderClient client = LocationServices
.getFusedLocationProviderClient(ctx);
//Define quality of service:
LocationRequest request = LocationRequest.create();
request.setInterval(1000); //Every second
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (locCallback != null) {
client.removeLocationUpdates(locCallback);
}
locCallback = createNewLocationCallback();
client.requestLocationUpdates(request, locCallback, null);
}
And this is the method for creating the Callback:
private LocationCallback createNewLocationCallback() {
LocationCallback locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult result) {
Location loc = result.getLastLocation();
// Do something with the location (may be null!)
}
};
return locationCallback;
}
Guess, I also found that somewhere as example, but did not keep the reference.
I do not have Oreo on my own. But some testers confirmed, that it works.
To keep the service in foreground, I am just calling "startForeground" afterwards in the onCreate method of my service.