我试图获得我的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