Issue in onLocationChanged() function of location listener of android.location.LocationListener.
In Below code after requesting requestLocationUpdates of LocationManager, the onLocationChanged is called in uneven intervals, i.e i have set period at 1 second but i don't receive the location change after every second.
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
@SuppressWarnings("MissingPermission")
public class SimplePositionProvider extends PositionProvider implements LocationListener {
public SimplePositionProvider(Context context, PositionListener listener) {
super(context, listener);
Log.i("SimplePositionProvider", "start");
if (!type.equals(LocationManager.NETWORK_PROVIDER)) {
type = LocationManager.GPS_PROVIDER;
}
}
public void startUpdates() {
Log.i("startUpdates", "start");
try {
Log.i("requestLocationUpdates", "start");
Log.i("TYPE", type);
locationManager.requestLocationUpdates(type, period, 0, this);
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "error");
}
}
public void stopUpdates() {
Log.i("stopUpdates", "start");
locationManager.removeUpdates(this);
}
@Override
public void onLocationChanged(Location location) {
Log.i("onLocationChanged", "start");
updateLocation(location);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.i("onStatusChanged", "start");
}
@Override
public void onProviderEnabled(String provider) {
Log.i("onProviderEnabled", "start");
}
@Override
public void onProviderDisabled(String provider) {
Log.i("onProviderDisabled", "start");
}
}
According to the tutorial, you should use FusedLocationProviderClient to request location updates. If memory serves, that solution sends updates at the specified interval. You can get a FusedLocationProviderClient
by calling LocationServices.getFusedLocationProviderClient(Context context)
.
You can set the request expiration duration in LocationRequest with setExpirationDuration
, and then use something like this code when you start the updates to re-start after each expiry:
Handler handler = new Handler(Looper.myLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (expectingLocationUpdates) {
restartLocationUpdates();
}
}
}, EXPIRATION_DURATION);