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

前端 未结 5 1527
面向向阳花
面向向阳花 2021-02-04 03:29

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

5条回答
  •  生来不讨喜
    2021-02-04 03:43

    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.

提交回复
热议问题