Getting null from 'getLastKnownLocation' on the SDK

I have a problem related to the Location API.

I tried the following code:

LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location loc = getLastKnownLocation(LocationManager.GPS_PROVIDER);

localways nullwhen called getLastKnownLocation().

What's wrong?

+5
source share
6 answers

Along with the permissions in your file, AndroidManifest.xmlhave you registered a location receiver?

LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location loc = getLastKnownLocation(LocationManager.GPS_PROVIDER);
lm.requestLocationUpdates(LocationManager.GPS, 100, 1, locationListener); 

Then in this case locationListener, to complete your task

private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
    latitude = location.getLatitude();
    longitude = location.getLongitude();
}
+6
source

If you use the code in the emulator, any calls to get the GPS location will return null until you explicitly update the location (via Eclipse or ADB ).

+3

, , Location, , , . GPS, , GPS , Location .

+2

Have you set permissions in your AndroidManifest.xml? These permissions are required to access the user's location with the application:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
+1
source

Here you can use:

LocationManager lm = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = lm.getBestProvider(criteria, false);
Location loc = lm.getLastKnownLocation(bestProvider);

last_lat = loc.getLatitude();
last_lng = loc.getLongitude();
0
source

You need an instance of LocationManager, for example:

First instance:

   LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

Wrong:

Location loc = getLastKnownLocation(LocationManager.GPS_PROVIDER);

Correctly:

Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
0
source

All Articles