Getting Location Updates based on time interval or Displacement
Asked Answered
K

1

6

I am using Fused Location Api to get location updates. When I set x seconds as time interval then I got onLocationChanged() called after every x seconds. And when I set 10 meter as minimumDisplacement then onLocationChanged() is not called until user moves 10 meter from its original position.

But I need to have onLocationChanged() called when either x seconds passed or 10 meter distance covered.

any idea how I can achieve this.

My Code

private Location mLastLocation;
public static final int REQUEST_LOCATION = 1006;
LocationRequest mLocationRequest;
private static final long POLLING_FREQ = 1000 * 10;
private static final long FASTEST_UPDATE_FREQ = 1000 * 10;
private static final long SMALLEST_DISPLACEMENT = 10;

mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(POLLING_FREQ);
        mLocationRequest.setFastestInterval(FASTEST_UPDATE_FREQ);
        mLocationRequest.setSmallestDisplacement(SMALLEST_DISPLACEMENT);

startLocationUpdates();
Kirstiekirstin answered 3/7, 2017 at 9:59 Comment(0)
T
11

Only for displacement

  mLocationRequest.setInterval(0);
  mLocationRequest.setFastestInterval(0);
  mLocationRequest.setSmallestDisplacement(SMALLEST_DISPLACEMENT);

Only for interval

 mLocationRequest.setInterval(POLLING_FREQ);
 mLocationRequest.setFastestInterval(FASTEST_UPDATE_FREQ);
 mLocationRequest.setSmallestDisplacement(0); // Not needed, already default value is 0

Normally interval and distance params are being calculated with AND. It means when you change your position at least SMALLEST_DISPLACEMENT meter AND at least POLLING_FREQ milliseconds have passed, then onLocationChanged() will be fired.

Towny answered 3/7, 2017 at 10:35 Comment(3)
I have a question regarding Service. I have to get location updates based on displacement (lets say 100 meters). After getting location updates I am getting list of latitude and longitude to create geo-fence. I was doing this task in a started service (without notification) but now I can not use started service, Android stops this anytime. So please suggest me how can I achive the functionality? I have tried JobSchedular, FirebaseJobDispatcher but they work periodically and when I kill the application it does’ not work.Shoa
@AshishTiwari The cure is foreground service. In normal background services, you are also limited to receive location updates and the service is candidate to be killed after a time. So being related to a view(notification - foreground service) will give you long life and full usage of location updates.Towny
Ok. Thank you @blackkara. I will try foreground service.Shoa

© 2022 - 2024 — McMap. All rights reserved.