我正在尝试在以下代码中检索我当前的位置坐标
LocationManager locationManager= (LocationManager) getSystemService(context);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
当提供者是“网络”时,我得到位置坐标。
当我更改位置和安全选项中的设置以启用“使用 GPS 卫星”选项时,提供商更改为“gps”。 在这种情况下,返回的位置为空。
这可能是什么原因造成的,如何解决?
最佳答案
GPS 提供商需要一段时间才能修复,尤其是在之前未进行修复的情况下。 getLastKnownLocation 不是阻塞调用,它会等到实际的实时 GPS 定位建立(该定位最多可能需要 1 分钟,具体取决于各种原因)。
此外,出于显而易见的原因,请确保您在室外)。
您首先需要向其请求位置更新,而不是简单地为 GPS 提供商调用 getLastKnownLocation。
下面这篇文章很好的解释了原理:http://developer.android.com/guide/topics/location/obtaining-user-location.html
对于在 Android 上使用位置提供程序进行任何操作的任何人来说,这都是必读的内容。
典型的流程是:
- 开始申请。
- 开始收听所需位置提供商的更新。
- 通过过滤掉新的但不太准确的修复来维持对位置的“当前最佳估计”。
- 停止监听位置更新。
- 利用最近的最佳位置估计。
查看下面的代码,我们正在初始化一个 MyLocationListener(以跟踪手机的位置),并检索对 LocationManager 的引用。我们正在请求 locationmanager 的位置更新。我们使用 10 米的 minDistance(通知的最小距离间隔)和 35 秒的 minTime(通知的最小时间间隔)。
LocationListener locationListener = new MyLocationListener();
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 35000, 10, this.locationListener);
实现此功能时,您可能会注意到 MyLocationListener 收到的更新比您预期的要多(给定 minTime 和 minDistance 参数)。以下文章在http://blog.doityourselfandroid.com/2010/12/25/understanding-locationlistener-android/可以帮助您理解原因。
关于java - 当提供者是 gps 时返回的位置为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5674414/