I'm using location services in an Android application I'm developing. After some research, I found out that getLastKnownLocation()
is the fastest way of getting a user's recent location. I have no problem it being a little outdated as the module of my application doesn't require a user's current location. This solution is fine for me as I don't really need the exact location of a user at that given moment.
But, the evident problem with getLastKnownLocation
is that it is bound to return null
if the device doesn't have recent location stored or if you've recently rebooted the device.
My question is, what to do when getLastKnownLocation
is null
?
This is what I have come up yet:
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
String bestProvider = lm.getBestProvider(criteria, false);
Location l = lm.getLastKnownLocation(bestProvider);
if(l != null) {
Log.d("Lat", String.valueOf(l.getLatitude()));
Log.d("Lng", String.valueOf(l.getLongitude()));
}
else {
PendingIntent pi = PendingIntent.getBroadcast(this, 0, new Intent(),
PendingIntent.FLAG_UPDATE_CURRENT);
lm.requestSingleUpdate(bestProvider, pi);
Location ln = lm.getLastKnownLocation(lm.getBestProvider(criteria, false));
// Still returns null
Log.d("NewLat", String.valueOf(ln.getLatitude()));
Log.d("NewLng", String.valueOf(ln.getLongitude()));
}
So, shouldn't the call to reqyestSingleUpdate
store the latest location data? It doesn't seem to be working, though.
Where am I going wrong? How'd you solve this problem?