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
I had been experiencing this issue on emulated devices running 7.0 and 8.0 and consistently the location callback was not being triggered when the screen was off (cmd+P). I was finally able to get my hands on a real 7.0 device (Galaxy S7) and I was not able to replicate the issue. Sorry if I wasted anyone's time, apparently it is an emulator issue.
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.
I had the same issue and I have found a working solution. In order to listen to location updates, you should NOT call this method:
public Task<Void> requestLocationUpdates (LocationRequest request,
LocationCallback callback, Looper looper)
You should use a pending intent instead of a callback, i.e. you should call the method:
public Task<Void> requestLocationUpdates (LocationRequest request,
PendingIntent callbackIntent)
Checkout the link to read more: https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient.html#requestLocationUpdates(com.google.android.gms.location.LocationRequest, android.app.PendingIntent)
one solution might be this :
check if location is not received in 2 minutes stop/start whole start location update again . although foreground service must have solve the problem
I've spent the past week trying to get Location Services in Foreground. Finally got it working by including this in the manifest.
android:foregroundServiceType="location"
I hope this can help someone in the future!