Foreground service not receiving location updates in Android 7.0+ when screen is off

南笙酒味 提交于 2019-12-03 03:27:15

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)

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!