Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

cesarruelas
cesarruelas
27,718 Points

A better method that getLastKnownLocation()?

I tried implementing location detection and it works for the most part except for one little thing. This is the method I used:

private Location getLocation() {
        Location location = null;

        try {
            if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            } else if (mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (location == null) {
            location = new Location("dummyprovider");
            location.setLatitude(37.8267);
            location.setLongitude(-122.423);
        }

        return location;
    }

However, the following occurs when testing with my Android 4.2 device: -If GPS isn't enabled, it gives back the default SF location -When I enable the GPS it will still give back the default SF location UNTIL I open the google maps app and click "find me"

I guess my question is how can I make the device give me its current location and not the last location registered in either the GPS or the network? My guess is that the problem is that there is no "last location" even when the GPS is enabled so it just gives back the SF default location.

1 Answer

Ben Jakuben
STAFF
Ben Jakuben
Treehouse Teacher

Did you try out a LocationListener like in the "Requesting Location Updates" section in The Beginner's Guide to Location in Android?