Search code examples
javaandroidgpsandroid-locationandroid-gps

Android GpsStatus always has zero satellites


I'm trying to get the satellites used in a GPS fix to get more information, but the GpsStatus.getSatellites() method always returns an empty iterator, even though I can get the location's latitude/longitude/altitude just fine.

LocationManager locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

if (location != null) {

    //get location coordinates
    mLatitude = location.getLatitude();
    mLongitude = location.getLongitude();
    double altitude = location.getAltitude();
    Log.d("test2", "lat : " + mLatitude);
    Log.d("test2", "long : " + mLongitude);

    //get satellite data
    GpsStatus gpsStatus = locationManager.getGpsStatus(null);

    int satellites = 0;
    int satellitesInFix = 0;
    int timetofix = gpsStatus.getTimeToFirstFix();
    Log.d("test2", "Time to first fix = " + timetofix);
    for (GpsSatellite sat : gpsStatus.getSatellites()) {
        if(sat.usedInFix()) {
            satellitesInFix++;
        }
        satellites++;
    }
    Log.d("test2", "Satellites: " + satellitesInFix + "/" + satellites);
}

All I get in the debug log is the following, over and over again:

09-06 18:42:48.093 6842-6842/com.android.example.gpstest D/test2: lat : 39.509401143731274
09-06 18:42:48.093 6842-6842/com.android.example.gpstest D/test2: long : -9.064780960816815
09-06 18:42:48.094 6842-6842/com.android.example.gpstest D/test2: Time to first fix = 0
09-06 18:42:48.095 6842-6842/com.android.example.gpstest D/test2: Satellites: 0/0

I already tried with multiple devices, thinking it might be some quirk with a particular model, but they all have the same issue, so it seems like my code isn't right. What do I need to do to get the satellites?


Solution

  • Because you haven't started GPS. getLastKnownLocation does not turn on GPS, it only returns a cached value, if any. You need to requestLocationUpdates to do so.