问题
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