我正在尝试查找 Android 项目的当前位置。加载应用程序时,我的当前位置始终为空。我已经在清单等中设置了权限。当我找到当前位置时,我打算使用坐标来查找到地图上其他位置的距离。我的代码片段如下。为什么我总是得到空值?
locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
towers = locMan.getBestProvider(crit, false);
location = locMan.getLastKnownLocation(towers);
if (location != null) {
System.out.println("Location is not null!");
lat = (int) (location.getLatitude() *1E6);
longi = (int) (location.getLongitude() * 1E6);
GeoPoint ourLocation = new GeoPoint(lati, longi);
OverlayItem overlayItem = new OverlayItem(ourLocation, "1st String",
"2nd String");
CustomPinpoint custom = new CustomPinpoint(d, MainMap.this);
custom.insertPinpoint(overlayItem);
overlayList.add(custom);
overlayList.clear();
} else {
System.out.println("Location is null! " + towers);
Toast.makeText(MainMap.this, "Couldn't get provider",Toast.LENGTH_SHORT)
.show();
}
getLastKnownLocation()
使用其他应用程序先前找到的位置。如果没有应用程序执行此操作,那么getLastKnownLocation()
将返回 null。
您可以对代码做一件事,以便有更好的机会获得最后已知的位置 - 迭代所有启用的提供程序,而不仅仅是最好的提供程序。例如,
private Location getLastKnownLocation() {
List<String> providers = mLocationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = mLocationManager.getLastKnownLocation(provider);
ALog.d("last known location, provider: %s, location: %s", provider,
l);
if (l == null) {
continue;
}
if (bestLocation == null
|| l.getAccuracy() < bestLocation.getAccuracy()) {
ALog.d("found best last known location: %s", l);
bestLocation = l;
}
}
if (bestLocation == null) {
return null;
}
return bestLocation;
}
如果您的应用程序在没有位置的情况下无法处理,并且没有最后已知的位置,则您将需要侦听位置更新。你可以看一下这个类的例子,
https://github.com/farble1670/autobright/blob/master/src/org/jtb/autobright/EventService.java
查看方法onStartCommand()
,它检查网络提供商是否已启用。如果没有,它将使用最后已知的位置。如果启用,它会注册以接收位置更新。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)