How can I check the current status of the GPS receiver?

前端 未结 17 1867
时光取名叫无心
时光取名叫无心 2020-11-22 08:53

How can I check the current status of the GPS receiver? I already checked the LocationListener onStatusChanged method but somehow it seems that is not working,

17条回答
  •  臣服心动
    2020-11-22 09:44

    I may be wrong but it seems people seem to be going way off-topic for

    i just need to know if the gps icon at the top of the screen is blinking (no actual fix)

    That is easily done with

    LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
    boolean gps_on = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
    

    To see if you have a solid fix, things get a little trickier:

    public class whatever extends Activity {
        LocationManager lm;
        Location loc;
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);        
            lm = (LocationManager) getSystemService(LOCATION_SERVICE);
            loc = null;
            request_updates();        
        }
    
        private void request_updates() {
            if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                // GPS is enabled on device so lets add a loopback for this locationmanager
                lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0, 0, locationListener);
            }      
        }
    
        LocationListener locationListener = new LocationListener() {
            public void onLocationChanged(Location location) {
                // Each time the location is changed we assign loc
                loc = location;
            }
    
             // Need these even if they do nothing. Can't remember why.
             public void onProviderDisabled(String arg0) {}
             public void onProviderEnabled(String provider) {}
             public void onStatusChanged(String provider, int status, Bundle extras) {}
        };
    

    Now whenever you want to see if you have fix?

    if (loc != null){
        // Our location has changed at least once
        blah.....
    }
    

    If you want to be fancy you can always have a timeout using System.currentTimeMillis() and loc.getTime()

    Works reliably, at least on an N1 since 2.1.

提交回复
热议问题