Why does the LocationManager does not have a lastKnown location?

后端 未结 2 397
星月不相逢
星月不相逢 2021-01-23 12:15

I want the location of user and that too just once after that user navigates on his own

locationManager = (LocationManager)this.getSystemService(LOCATION_SERVICE         


        
相关标签:
2条回答
  • 2021-01-23 12:28

    The getLastKnownLocation method will only return a location if the gps LocationProvider has stored a location somewhere. If the user has not yet used the gps on his device long enough to obtain a valid GPS fix the method will return null.

    Even if you retrieve a location check the time of the location, there is no guarantee that the location isn't very very old.

    0 讨论(0)
  • 2021-01-23 12:32

    It's not enough to just get a locationManager and call getLastKnownLocation() because until there is an update there will be no "last known location" You are missing that request provided by the LocationManager class:

    public void requestLocationUpdates(java.lang.String provider, 
                                       long minTime,
                                       float minDistance, 
                                       android.location.LocationListener listener) 
    

    If your activity implements LocationListener as mine did, you can pass in "this" as the LocationListener for a call originating in a method of that class. Otherwise, there are several other overloads taking Activity or Looper classes instead.

    locationManager.requestLocationUpdates(provider, minTime, minDistance, this);
    

    In order to make sure the device is getting a location, request updates - but you also may want to put guards for failure to find providers or getLastKnownLocation returning null.

    locationManager.requestLocationUpdates(provider, 1, 0, this);
    mostRecentLocation = locationManager.getLastKnownLocation(provider);
    if(mostRecentLocation == null)
    // lower your expectations, or send user message with Toast or something similar 
    

    Tell the user to turn on their location sharing or other provider services.

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