Search code examples
androidgpslocationmanagerlocationlistener

Android LocationListener no hitting onLocationChanged


I have a class named GPStracker which implements the LocationListener interface.

public class GPSTracker implements LocationListener {
    Context context;
    LocationManager lm;

In the constructor I set the LocationManager and some settings (I've omitted the permissions part):

public GPSTracker(Context c) {
    context = c;

    ... (Permission checking)

    lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    boolean isGPSEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    if(isGPSEnabled){
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 6000, 5, this);
    } else {
        Toast.makeText(context, "Please enable GPS", Toast.LENGTH_SHORT).show();
    }
}

In the manifest file I've set these permissions about the GPS:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

And I've some overridden methods of which only one has some functionality, the onLocationChanged method:

@Override
public void onLocationChanged(Location location) {
    InspectieOverzicht activity = (InspectieOverzicht) context;
    activity.getFirstFragment().updateDistance(location);
}

I create a new GPSTracker object in an activity.

g = new GPSTracker(this);

I expect this to work. It'll ask for permissions to use the GPS and I see in the top the GPS icon so it's working with the GPS. But the onLocationChanged method is never called.

I even tried walking up and down the building where I'm at (maybe it really needs to change) but that also didn't work.

I've tried it on a virtual device to change the GPS location and that works like a charm. It's updating my activity immediately.

I've tried it on API 19, 23 and 26 (on emulated devices) which all worked. I've tried it on API 23 on an actual device which doesn't seem to work.

Does anyone knows what I'm doing wrong here?


Solution

  • use both sometimes network provide coordinates if GPS_PROVIDER not works

      locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, mylistener);
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, mylistener);