我試圖獲得我的Android應用程序的位置,但getLastKnownLocation
總是返回null
和onLocationChanged
永遠不會被調用。我爲我的應用使用以下權限:Android的GPS跟蹤問題
ACCESS_NETWORK_STATE,
ACCESS_FINE_LOCATION ACCESS_COARSE_LOCATION.
GPS和互聯網已打開,在我的設備上。我也嘗試了requestLocationUpdates
的不同值。
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
locationManager.removeUpdates(this);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled)
{
// no network provider is enabled
}
else
{
hasGPS = true;
location = null;
if (isGPSEnabled)
{
if (location == null)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null)
{
lat = location.getLatitude();
lng = location.getLongitude();
}
}
}
}
if (isNetworkEnabled && location == null)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null)
{
lat = location.getLatitude();
lng = location.getLongitude();
}
}
}
}
這可能聽起來很傻,但你(即不使用仿真器)上的實際的手機測試正確呢? – jedwards
相關的,可能有助於[這裏](http://stackoverflow.com/questions/19621882/getlastknownlocation-returning-null)和[這裏](http://stackoverflow.com/questions/1608632/android-locationmanager-getlastknownlocation-返回空)。 – jedwards
是的,我用Android 4.1在平板電腦上試過這段代碼。 – user3629312