0
我需要獲取Android設備的位置。但有一些問題:getLastKnownLocation()
返回空值。也許問題在自定義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) {}
}
爲什麼我不能使用這種方法? – BoBaH6eToH
我並不是說你不必使用它們,但要知道,如果不利用Play服務,你將不得不多做一些工作。大多數情況下,Play服務算法可以滿足您在啓動應用程序時立即查詢位置所需的內容。如果您需要從零開始實施一切,您必須: getLastKnownLocation>檢查它是否滿足您的約束條件>如果不向一個/更多啓用的提供者詢問位置和管理故障,... –