Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android LocationManager.getLastKnownLocation() returns null

Tags:

android

gps

So I'm trying to sample the gps coordinates just once in an application. I don't want to create a LocationListener object to constantly get gps updates. I want to wait until receiving the coordinates, and then proceed on to another task.

Here is a code snippet

LocationManager lm = (LocationManager)act.getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
crit.setAccuracy(Criteria.ACCURACY_FINE);
String provider = lm.getBestProvider(crit, true);
Location loc = lm.getLastKnownLocation(provider);

The loc variable is always null in the emulator. I tried using the command "geo fix latitude longitude" to set it, and also I tried using the DDMS way of setting it. Neither method had any effect on the code. Also the snippet isn't causing any exceptions.

Thanks for your help.

like image 826
Robert Parker Avatar asked Oct 22 '09 17:10

Robert Parker


1 Answers

The call to request update for a location is not blocking, hence it wont wait there. Also the provider in emulator may not have been started.

A possible check could be to see if the settings in it disable gps provider ? then send geo fix.

However, I would use Location Listener, it would be ideal in your case since you need a geo fix to proceed further.Location Listener is Used for receiving notifications from the LocationManager when the location has changed. You can unregister the listener after first geofix.

Note: It can take some time on device to get current location, and even on device this can return null.

like image 55
krishc Avatar answered Nov 07 '22 06:11

krishc