Yep, getLastKnownLocation()
may well return null. The documentation says:
Returns a Location indicating the data from the last known location
fix obtained from the given provider.
This can be done without starting the provider. Note that this
location could be out-of-date, for example if the device was turned
off and moved to another location.
If the provider is currently disabled, null is returned.
An Android device does not automatically track its location all the time. The "last known location" is available only if some application has requested the location. So you should not expect to always get a location with getLastKnownLocation()
. And even if it returns something the location might not be up-to-date. The Location
object has a timestamp which you can read with the getTime()
method and an estimated accuracy which you can read with the getAccuracy()
method. These can be used to evaluate is the location usable.
If you receive null or a very old location you'll need to request a fresh location. The basic options are just requesting a single location update or continuous updates with a time interval that you can specify.
In either case your class needs to implement the LocationListener interface:
public class GpsTracker implements LocationListener {
// ...other code goes here...
@Override
public void onLocationChanged(Location location) {
// Do something with 'location' here.
}
}
For a single location update you would call [LocationManager.requestSingleUpdate()](http://developer.android.com/reference/android/location/LocationManager.html#requestSingleUpdate(java.lang.String, android.location.LocationListener, android.os.Looper)) and for continuous updates [LocationManager.requestLocationUpdates()](http://developer.android.com/reference/android/location/LocationManager.html#requestLocationUpdates(java.lang.String, long, float, android.location.LocationListener)). In either case there will be a small (or not so small) delay and the LocationListener.onLocationChanged() callback is called when a location is available.
For example you could request a single update from the GPS provider like this:
locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, this, null);
For continuous updates from the GPS provider max. every 1 second and only when the location has changed at least 1 meter you could call:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, this);
And then there are some more variations of the requestSingleUpdate()
which you can see in the documentation and on the other hand the Google Play services location APIs but let's not go there. Your question was about getLastKnownLocation()
returning null and Stack Overflow has several examples of different ways to request an up-to-date location.
EDIT: This is an old answer. The basic idea is still valid, but check out the Android documentation for modern ways to request location updates.