Steven97102 Steven97102 - 1 year ago 106
Java Question

Alternatives for getLastKnownLocation

I am using Google maps v2 and sometimes getLastKnownLocation() returns NULL. is there an alternative to have the same effect but with a higher stability? Thanks for helping

Answer Source

First of all, getLastKnownLocation() should only return null if the user has turned off location for your app (Marshmallow) or turned off location for all apps (Lollipop and below). Also, be sure to call locationManager.requestSingleUpdate() before calling getLastKnownLocation.

This is some pretty reliable code, (if I don't get a location within 5 attempts I assume we can't get the location):

if (ContextCompat.checkSelfPermission(context,
                Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
                && locMan != null) {

            String provider;

            provider = locMan.getProvider(LocationManager.NETWORK_PROVIDER).getName();

            if (Looper.myLooper() == null) {

            int count = 5;
            for (int i = 0; i < count; i++) {

                locMan.requestSingleUpdate(provider, locationListener, Looper.myLooper());
                location = locMan.getLastKnownLocation(provider);

                if (location != null) {
                } else {
                    try {
                    } catch (InterruptedException e) {

An alternative, you can apply for location updates using locationManager.requestLocationUpdates() and give it a LocationListener. The listener will fire when the OS gets a location update.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download