93

I've read some questions about this, but I didn't quite find an answer that I needed.

So, the case is that I have my map set up, and I want to grab my current gps location. I have checked that my variables is not NULL but yet my result from:

getLastKnownLocation(provider, false);

Gives me null though, so this is where I need help. I have added permissions for COARSE + FINE location. But I usually have all kinds of network data disabled for my phone, because I'm not very happy about unpredictable dataflow expenses in my phone bill. So I have only WiFi enabled and connected for this test.

Is there anything more I NEED to enable in order for this to be possible? I would think WiFi should be sufficient?

Kara
  • 6,115
  • 16
  • 50
  • 57
Aleksander Fimreite
  • 1,439
  • 2
  • 18
  • 31

9 Answers9

212

Use this method to get the last known location:

LocationManager mLocationManager;
Location myLocation = getLastKnownLocation();

private Location getLastKnownLocation() {
    mLocationManager = (LocationManager)getApplicationContext().getSystemService(LOCATION_SERVICE);
    List<String> providers = mLocationManager.getProviders(true);
    Location bestLocation = null;
    for (String provider : providers) {
        Location l = mLocationManager.getLastKnownLocation(provider);
        if (l == null) {
            continue;
        }
        if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
            // Found best last known location: %s", l);
            bestLocation = l;
        }
    }
    return bestLocation;
}
C--
  • 16,393
  • 6
  • 53
  • 60
TharakaNirmana
  • 10,237
  • 8
  • 50
  • 69
  • 2
    Turns out I had it correct all along, I just noticed an error that I found an solution to this. I did not have my phone set to allow Google Position for GPS. So, yeah. Thanks anyways =) – Aleksander Fimreite Dec 15 '13 at 00:20
  • 1
    enable location in the phone. – TharakaNirmana Jul 04 '16 at 04:02
  • 29
    question is about `getLastKnownLocation returns null` ... this code will change nothing ... if for all providers `mLocationManager.getLastKnownLocation` **(as it can return null)** it will still returns null ... **answer is ... sorry you cannot avoid this ... if you really want the location do not use getLastKnownLocation** – Selvin Dec 15 '16 at 11:36
  • I was calling it from service class and faced nullPointer on getApplicationContext(). So using context of the activity class solved my problem. – Rahul Hawge May 24 '17 at 06:52
  • It should be `l.getAccuracy() > bestLocation.getAccuracy()`. – Chaitanya Shah Nov 23 '17 at 15:44
  • without enable gps how to get lastknownlocation? – Makvin Oct 17 '18 at 07:42
  • 1
    Perfectly worked for me. Just need to have permissions wrapper. – Haroon khan Mar 20 '19 at 09:04
  • 1
    Worth reading this answer, if the code doesn't work for you : https://stackoverflow.com/a/38794291/5319831 – Mohd Naved Nov 12 '19 at 09:00
33

you are mixing the new and the old location API's together when you shouldnt.

to get the last known location all your have to do is call

compile "com.google.android.gms:play-services-location:11.0.1"
mLocationClient.getLastLocation();

once the location service was connected.

read how to use the new location API

http://developer.android.com/training/location/retrieve-current.html#GetLocation

 private void getLastLocationNewMethod(){
    FusedLocationProviderClient mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    mFusedLocationClient.getLastLocation()
            .addOnSuccessListener(new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    // GPS location can be null if GPS is switched off
                    if (location != null) {
                        getAddress(location);
                    }
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.d("MapDemoActivity", "Error trying to get last GPS location");
                    e.printStackTrace();
                }
            });
}
Binesh Kumar
  • 2,763
  • 1
  • 16
  • 23
8

You are trying to get the cached location from the Network Provider. You have to wait for a few minutes till you get a valid fix. Since the Network Provider's cache is empty, you are obviously getting a null there..

Sagar Maiyad
  • 12,655
  • 9
  • 63
  • 99
1

Add this code

if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
     return;
}

before the function:

locationManagerObject.requestLocationUpdates(LocationManager.GPS_PROVIDER, MINIMUM_TIME_BETWEEN_UPDATES, MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, new LocationListener()) as well as the function: locationManagerObject.getLastKnownLocation(LocationManager.GPS_PROVIDER)

Abdulla Nilam
  • 36,589
  • 17
  • 64
  • 85
Krupa Kakkad
  • 857
  • 1
  • 13
  • 28
1

Try this it works good for me :-

LocationManager mLocationManager;
Location myLocation = getLastKnownLocation();

        private Location getLastKnownLocation() {
            Location oldLoc;
            while (true){
                oldLoc = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                if (oldLoc == null){
                    continue;
                }
                else {
                    break;
                }
            }
            return oldLoc;
        }

You can use NETWORK_PROVIDER in place of GPS_PROVIDER for faster results..

Mohammad Kholghi
  • 533
  • 2
  • 7
  • 21
Sumit
  • 143
  • 8
1
private void getLastLocation()
{
    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);


    LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            Log.e("location",location.getLatitude()+"");

        }

        public void onStatusChanged(String provider, int status, Bundle extras) {}

        public void onProviderEnabled(String provider) {}

        public void onProviderDisabled(String provider) {}
    };

    locationManager.requestSingleUpdate(LocationManager.NETWORK_PROVIDER,locationListener,null);

}

// This will help you for fetching location after gps enable

locationManager.requestSingleUpdate(LocationManager.NETWORK_PROVIDER,locationListener,null);

shubomb
  • 672
  • 7
  • 20
0

I had this problem in Xamarin.Android.

Location location = locationManager.GetLastKnownLocation(provider); was returning null value. I checked my code and got to know that I had just requested permission for ACCESS_COARSE_LOCATION. I added code to request permission for ACCESS_FINE_LOCATION and now it was not returning null. Here is my code:

void AskPermissions()
{
    if (CheckSelfPermission(Manifest.Permission.AccessCoarseLocation) != (int)Permission.Granted ||
            CheckSelfPermission(Manifest.Permission.AccessFineLocation) != (int)Permission.Granted)
        RequestPermissions(new string[] { Manifest.Permission.AccessCoarseLocation, Manifest.Permission.AccessFineLocation }, 0);
    else
        GetLocation();
}

public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
    if (CheckSelfPermission(Manifest.Permission.AccessCoarseLocation) == (int)Permission.Granted &&
            CheckSelfPermission(Manifest.Permission.AccessFineLocation) == (int)Permission.Granted)
        GetLocation();
    else
        Log.Info(tag, "Permission not Granted: Please enter desired Location manually.");
}

void GetLocation()
{
    locationManager = (LocationManager)GetSystemService(LocationService);
    provider = locationManager.GetBestProvider(new Criteria(), false);
    Location location = locationManager.GetLastKnownLocation(provider);
    if (location != null)
        Log.Info(tag, "Location Lat: " + location.Latitude + " Lon: " + location.Longitude);
    else
        Log.Info(tag, "Location is null");
}

In case anyone coming from Xamarin.Android (C#) would find it useful. For Java or Android Studio the code would be similar withs some minor Syntax changes like GetLastKnownLocation() will be getLastKnownLocation() as method names in Java start with lowercase letters while in C# method names start with Uppercase letters.

Junaid Pathan
  • 3,850
  • 1
  • 25
  • 47
0

I liked this solution to update location:

Update location

In resume, add the condition:

Location myLocation = getLastKnownLocation();
if (myLocation == null) {
      locationManager.requestLocationUpdates(
      LocationManager.PASSIVE_PROVIDER,
      MIN_TIME_BW_UPDATES,
      MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
      Log.d("GPS", "GPS Enabled");
 }

And maybe is some basic, but check that GPS is ON.

-4

Replace ur line with

Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
Deepak Vajpayee
  • 348
  • 2
  • 4
  • 15