检测位置有什么问题?

时间:2014-01-31 09:46:55

标签: java android location locationlistener

我需要获取Android设备的位置。但是它有一些问题:getLastKnownLocation()返回null值。自定义LocationListener中可能存在问题,但我不知道如何修复它。有人可以帮帮我吗?

这是我的代码:

MainActivity:

locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

private Pair <String, String>  getLocation()
{
    Pair< String, String > result = Pair.create("null", "null");
    GeoLocatorListener geoLocatorListener = new GeoLocatorListener();
    Location currentLocation;
    Boolean isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    Boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    if ( !isGpsEnabled && !isNetworkEnabled )
        return result;

    long minWaitTime = 1000 * 10;       // 10 minutes
    float minDistance = 100;            // 100 metres

    if ( isGpsEnabled )
    {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minWaitTime, minDistance, geoLocatorListener);
        currentLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    }
    else
    {
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, minWaitTime, minDistance, geoLocatorListener);
        currentLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    }
    if ( currentLocation != null )
        return Pair.create(String.valueOf(currentLocation.getAltitude()),String.valueOf(currentLocation.getLongitude()));
    return result;
}

自定义LocationListener课程 - GeoLocatorListener

public class GeoLocatorListener implements LocationListener {
@Override
public void onLocationChanged(Location location) {}
@Override
public void onProviderDisabled(String provider) {}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}

1 个答案:

答案 0 :(得分:0)

基本上当你要求 lastKnownLocation()时,你可以找回一个位置或null。您需要检查的另一件事是您的位置已更新,因为它可能已经过时了。

我想/假设您正在开发一个可以在安装了Google Play的设备上运行的应用程序(+ GooglePlay服务),因此我建议您查看fused location

通过这种方式,您可以委托并利用GooglePlay服务来检索您的位置,从而消除您在使用基于位置的应用时产生的所有算法和问题。

相关问题