Why does the LocationManager does not have a lastKnown location?

纵饮孤独 提交于 2019-12-04 05:12:08

问题


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

locationManager = (LocationManager)this.getSystemService(LOCATION_SERVICE);
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
if (location != null) {
   System.out.println(location.toString());
   lat=location.getLatitude();
   lng=location.getLongitude();
}     
p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));

However i am not able to get the location of the user is it because of slow internet connection from the mobile ??


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/6166317/why-does-the-locationmanager-does-not-have-a-lastknown-location

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!