MarcForn
MarcForn

Reputation: 3409

Error getting Location Android (GPS and Network)

I want to get the location in my APP using the following code:

public Location getLocation() {     

    boolean isGPSEnabled     = false;
    boolean isNetworkEnabled = false;

    try {   

        // Getting GPS and Network status
        isGPSEnabled     = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) return null;

        LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        location                = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        if ((location != null && (location.getTime() + 60000 < System.currentTimeMillis())) || 
                location == null){
            location = manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        }                           

    } catch (Exception e) {
        e.printStackTrace(); 
        return null;
    }

    return location;
}

When I am using a Nexus 4 it works properly and location has a value. But when I am executing the same code in a Galaxy S2 location = null.

Before calling the function I have checked that GPS and Network are both enabled.

How would you correcte this function?

Before calling this function I call this one:

public void startLocation() {

    try {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);    

    } catch (Exception e) {
        e.printStackTrace(); 
    }
}

Upvotes: 0

Views: 2407

Answers (2)

cYrixmorten
cYrixmorten

Reputation: 7108

If the device have not yet found a location, it will return null.

I bet if your open Google Maps and let it locate you before opening your app, it will work as expected.

See my answer to Location servise GPS Force closed. This is an example on how you can implement a callback to let you know as soon as a location is available.

Upvotes: 2

wvdz
wvdz

Reputation: 16651

I think you have to trigger it by calling one of the .request... functions.

Upvotes: 0

Related Questions