Steven97102 Steven97102 - 2 months ago 11
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

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) {
                Looper.prepare();
            }

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

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

                if (location != null) {
                    break;
                } else {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

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.

Comments