Error getting Location Android (GPS and Network)

谁都会走 提交于 2019-11-28 12:21:18

问题


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(); 
    }
}

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/19825256/error-getting-location-android-gps-and-network

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!