【发布时间】:2014-05-12 16:28:32
【问题描述】:
我试图为我的 android 应用程序获取位置,但 getLastKnownLocation 总是返回 null 并且永远不会调用 onLocationChanged。我对我的应用使用以下权限:
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();
}
}
}
}
【问题讨论】:
-
这听起来可能很傻,但您是在实际的手机上正确地测试它(即,不使用模拟器)?
-
是的,我在装有 android 4.1 的平板电脑上尝试了此代码
-
安装一个知名的 Android 应用程序,您可以在其中查看 GPS 是否正常工作。顺便说一句,您的位置更新监听器在哪里?