Android - Reliably getting the current location

后端 未结 2 509
既然无缘
既然无缘 2020-12-08 09:04

My app checks at a specific time whether a user is at a given location. I use the alarm manager to start a service that makes this call:

locationManager.requ         


        
相关标签:
2条回答
  • 2020-12-08 09:29

    If the user's location is already stable, then getLastKnownLocation will return the current location. I'd call getLastKnownLocation first, look at the timestamp (compare Location.getElapsedRealTimeNanos() with SystemClock.elapsedRealTimeNanos()) then register a listener if the fix is too old.

    0 讨论(0)
  • 2020-12-08 09:47

    The code may be something like that:

    public class MyLocation {
        Timer timer1;
        LocationManager lm;
    
        public boolean getLocation(Context context)
        {
            lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
            timer1=new Timer();
            timer1.schedule(new GetLastLocation(), 20000);
            return true;
        }
    
        LocationListener locationListenerGps = new LocationListener() {
            public void onLocationChanged(Location location) {
                timer1.cancel();
                lm.removeUpdates(this);
                //use location as it is the latest value
            }
            public void onProviderDisabled(String provider) {}
            public void onProviderEnabled(String provider) {}
            public void onStatusChanged(String provider, int status, Bundle extras) {}
        };
    
        class GetLastLocation extends TimerTask {
            @Override
            public void run() {
                 lm.removeUpdates(locationListenerGps);
                 Location location=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                 //use location as we have not received the new value from listener
            }
        }
    }
    

    We start the listener and wait for update for some time (20 seconds in my example). If we receive update during this time we use it. If we don't receive an update during this time we use getLastKnownLocation value and stop the listener.

    You can see my complete code here What is the simplest and most robust way to get the user's current location on Android?

    EDIT (by asker): This is most of the answer, but my final solution uses a Handler instead of a Timer.

    0 讨论(0)
提交回复
热议问题