java Android GPS跟踪问题
我试图为我的安卓应用程序获取位置,但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();
}
}
}
}
# 1 楼答案
GPS信号无法穿透墙壁,因此通常在建筑物内不起作用
出于开发和测试目的,您可以使用Android模拟位置: http://developer.android.com/training/location/location-testing.html
# 2 楼答案
如果GetLastKnownLocation从未通过该提供程序获得过位置,或者位置太旧,则GetLastKnownLocation将返回null。所以这并不意外。最有可能的情况是,你没有收到GPS信号,这可能需要几秒钟或几分钟(或者在许多建筑中完全失败)。再次检查GPS是否已在“设置”中打开,并查看通知区域中的闪烁圆圈——如果它从未变为实心,则您不会收到信号