我正在开发一个使用当前用户位置获取结果的Android应用。
我使用以下代码获取位置:
LocationManager locationManager =
(LocationManager) getSystemService(LOCATION_SERVICE);
Location currentLocation =
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
当我在设备上运行它时,它给我一个位置的空值。
但是,当我使用NETWORK_PROVIDER
它工作正常时,设备是否有额外设置才能使用GPS?
我的设备是Galaxy Tab P-1000。
答案 0 :(得分:5)
使用getLastKnownLocation()
调用GPS_PROVIDER
会返回缓存值。如果没有最近的位置,它将返回null。请改用LocationListener
的{{1}}回调。
可能需要一段时间,但你会得到一个新的定位。
onLocationChanged()
的位置并不总是准确的,因为它基于细胞网站三角测量
答案 1 :(得分:2)
使用:
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();
}
}
我在我的代码中使用了它,效果很好。