Search code examples
androidandroid-location

Getting GPS strength in Android


In my app, I have to find out GPS strength. However, when I use the following code, I get 0 only for count no of satellites. So, I could not get GPS strength.

My code:

public void onCreate(Bundle savedInstanceState) {
  locMgr = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
  locMgr.addGpsStatusListener(onGpsStatusChange) ;
  onGpsStatusChange.onGpsStatusChanged(GpsStatus.GPS_EVENT_SATELLITE_STATUS);                     
 // Listener for GPS Status...
}

            final Listener onGpsStatusChange=new GpsStatus.Listener()
            {       
                    public void onGpsStatusChanged(int event)
                    {
                        Log.e("gps","in class");
                            switch(event)
                            {
                             case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
                                  GpsStatus xGpsStatus =locMgr.getGpsStatus(null) ;

                                  Iterable<GpsSatellite> iSatellites               =xGpsStatus.getSatellites();
                                  Iterator<GpsSatellite> it = iSatellites.iterator();
                                   int count=0;
                                   while(it.hasNext()){
                                    count=count+1;
                                        GpsSatellite oSat = (GpsSatellite) it.next();
                                        

                                        Log.e("gps",""+oSat.getSnr());   
                                   }
                                 Log.e("count",""+count);
                                 tv1.setText(""+count);
                             break;
                            }
                    }
            };

Solution

  • private class MyGPSListener implements GpsStatus.Listener {
        public void onGpsStatusChanged(int event) {
            switch (event) {
                case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
                    if (mLastLocation != null)
                        isGPSFix = (SystemClock.elapsedRealtime() - mLastLocationMillis) < 3000;
    
                    if (isGPSFix) { // A fix has been acquired.
                        // Do something.
                    } else { // The fix has been lost.
                        // Do something.
                    }
    
                    break;
                case GpsStatus.GPS_EVENT_FIRST_FIX:
                    // Do something.
                    isGPSFix = true;
    
                    break;
            }
        }
    }
    

    OK, now in onLocationChanged() you should add the following:

    @Override
    public void onLocationChanged(Location location) {
        if (location == null) return;
        mLastLocationMillis = SystemClock.elapsedRealtime();
        // Do something.
        mLastLocation = location;
    }