[英]Problem using GPS_PROVIDER for location
我正在开发一个 Android 应用程序,它使用当前用户位置作为结果。
我正在使用以下代码来获取位置:
LocationManager locationManager =
(LocationManager) getSystemService(LOCATION_SERVICE);
Location currentLocation =
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
当我在设备上运行它时,它会给我一个 null 位置值。
但是当我使用NETWORK_PROVIDER
时它工作正常,是否有任何额外的设置让设备使用 GPS?
我的设备是 Galaxy Tab P-1000。
使用GPS_PROVIDER
调用getLastKnownLocation()
会返回一个缓存值。 如果没有最近的位置,它将返回 null。 请改用LocationListener
的onLocationChanged()
回调。
这可能需要一段时间,但您会得到一个全新的 position 修复程序。
NETWORK_PROVIDER
的位置并不总是准确的,因为它基于蜂窝站点三角测量
利用:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
对于 locationListener,您可以使用:
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location
// provider.
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude());
Toast.makeText(LbsGeocodingActivity.this, message,
Toast.LENGTH_LONG).show();
if (location != null) {
GeoPoint point2 = new GeoPoint(
(int) (location.getLatitude() * 1E6), (int) (location
.getLongitude() * 1E6));
// Toast.makeText(getBaseContext(),
// "Latitude: " + location.getLatitude() +
// " Longitude: " + location.getLongitude(),
// Toast.LENGTH_SHORT).show();
//
mapView.getController().animateTo(point2);
mapView.getController().setZoom(15);
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = LbsGeocodingActivity.this.getResources()
.getDrawable(R.drawable.new3pin);
HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(
drawable, LbsGeocodingActivity.this);
point = new GeoPoint((int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6));
String address = convertPointToLocation(point);
String delims = ",";
String[] tokens = address.split(delims);
OverlayItem overlayitem = null;
if(tokens.length==1)
{
overlayitem = new OverlayItem(point,
"New Location", "Locality:"+"\nCity:"+"\nCountry: "+tokens[0]);
}
else if(tokens.length==2)
{
overlayitem = new OverlayItem(point,
"New Location", "Locality:"+"\nCity: "+tokens[0]+"\nCountry: "+tokens[1]);
}
else if(tokens.length==3)
{
overlayitem = new OverlayItem(point,
"New Location", "Locality: "+tokens[0]+"\nCity: "+tokens[1]+"\nCountry: "+tokens[2]);
}
else
{
overlayitem = new OverlayItem(point,
"New Location", address);
}
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.clear();
mapOverlays.add(itemizedoverlay);
// mapView.invalidate();
}
}
我在我的代码中使用了它,它运行良好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.