简体   繁体   中英

android getLastKnownLocation() return always return null

I am creating an app that only checks for location when user clicks a button.

here is my code, and it returns null when i call getLastKnownLocation, even after I call requestLocationUpdates:

public void main(String[] args, int iteration, Context context){
    Criteria criteria = new Criteria();
    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

    LocationListener loc_listener = new LocationListener() {
        public void onLocationChanged(Location l) {
        }
        public void onProviderEnabled(String p) {}
        public void onProviderDisabled(String p) {}
        public void onStatusChanged(String p, int status, Bundle extras) {}

        };

    String bestProvider = locationManager.getBestProvider(criteria, false);
    locationManager.requestLocationUpdates(bestProvider, 0, 0, loc_listener);
    Location location = locationManager.getLastKnownLocation(bestProvider);
    location = locationManager.getLastKnownLocation(bestProvider);
    double lat;
    double lon;
    try {
        lat = location.getLatitude();
        lon = location.getLongitude();

    } catch (NullPointerException e) {
        lat = -1.0;
        lon = -1.0;

    }
    Log.i("results:",  String.valueOf(lat) + " " + String.valueOf(lon) + " 10NN");}}

the location service on the device is enabled. Thanks very much!

getLastKnownLocation will return null until the callback onLocationChanged() is triggered. This may take several minutes for GPS, even if the sky is clearly visible. If you are indoors it may never run. You have to wait for it to run.

try this pls

  mGoogleMap.setOnMyLocationButtonClickListener(new OnMyLocationButtonClickListener() {

                    @Override
                    public boolean onMyLocationButtonClick()
                        {

                            Location myLocation = mGoogleMap.getMyLocation();
                            onLocationChanged(myLocation);
                            return false;
                        }
                });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM