Get GPS Location instantly via Android app

前端 未结 4 982
灰色年华
灰色年华 2020-12-20 06:47

all. I am writing an android app about GPS locations.

I tried it on emulator and entered the latitude and longitude manually, and it worked fine. However, my problem

4条回答
  •  無奈伤痛
    2020-12-20 07:31

    The getLastKnownLocation method does not trigger an onLocationChanged event. One way to refactor your code would be to move the logic that acts on a Location to a separate method and then call that method both after you call getLastKnownLocation, and from your onLocationChanged method.

    Bear in mind that there is no guarantee that getLastKnownLocation will provide a meaningful Location, since you the device might have moved since the last location update.

    Example code:

    public void onCreate(Bundle savedInstanceState){
        ....
        String provider = LocationManager.GPS_PROVIDER;
        Location location = locationManager.getLastKnownLocation(provider);
        updateLocation(location);
    }
    
    public class MyLocationUpdater implements LocationListener{ //change location interface
        @Override
        public void onLocationChanged(Location location) {
            updateLocation(location);
        }
        ...
    }
    
    void updateLocation(Location location) {
        Double lat = location.getLatitude();
        Double lon = location.getLongitude();
    
        // the rest of the code from onLocationChanged
    }
    

提交回复
热议问题