我不明白为什么locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
返回位置null。我给了所有的许可,但它的reutening null
。
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
我有同样的问题。这是因为我的设备没有存储最后一个已知位置。我只是转到Google地图并使用GPS精确定位我的位置,然后为getLastKnownLocation()返回了一个值
您可以请求这样的位置更新
mLocationManager.requestLocationUpdates(myProvider, 0, 0, locationListener);
然后在locationListener.onLocationChanged
的第一个回调设置你的坐标。只是不要忘记打电话给mLocationManager.removeUpdates(locationListener)
如果设备不知道最后的已知位置,则返回documentation,它返回null。可能GPS无法找到你。无论如何,它需要大约一分钟或更长时间。因此,在晴朗的天空下,远离高层建筑,尝试外出,等到GPS可以找到你。
我使用这种方法来获取位置,我认为它会对你有所帮助
private void startReceivingLocationUpdates() {
if (mLocationManager == null) {
mLocationManager = (android.location.LocationManager)
mContext.getSystemService(Context.LOCATION_SERVICE);
}
if (mLocationManager != null) {
try {
mLocationManager.requestLocationUpdates(
android.location.LocationManager.NETWORK_PROVIDER,
1000,
0F,
mLocationListeners[1]);
}
catch (SecurityException ex)
{
Log.i(TAG, "fail to request location update, ignore", ex);
}
catch (IllegalArgumentException ex)
{
Log.d(TAG, "provider does not exist " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
android.location.LocationManager.GPS_PROVIDER,
1000,
0F,
mLocationListeners[0]);
if (mListener != null) mListener.showGpsOnScreenIndicator(false);
}
catch (SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex); }
catch (IllegalArgumentException ex) {
Log.d(TAG, "provider does not exist " + ex.getMessage()); }
Log.d(TAG, "startReceivingLocationUpdates");
}
}
当您使用GPS作为提供商时,它会为您的结果提供1到2个mnt,因此您必须在获取位置时进行有争议的检查,并且网络提供商会在您请求时立即为您提供位置。因此,您不会立即获得GPS提供商的位置lat lon。
GPS只需要第一次使用1到2,然后它会给你随叫随到的位置......