标签:
android关于LocationManager的gps定位
LocationManager提供了两种定位当前位置的方法 GPS和NETWORK 其中gps的误差大概50m左右 network大概500m
起初当gps打开后 我使用Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);来获取location 可是一直为null不知道是什么原因 网上搜了很久终于找到了解决方案
android有一个Criteria类可以直接判断当前适合用gps或者network 并且设置LocationListener监听器实时更新location 直接上代码
private void getLocalAddress() {
LocationManager locationManager;
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
//updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 2000, 10,
locationListener);
updateWithNewLocation(location);
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
private void updateWithNewLocation(Location location) {
String latLongString;
TextView myLocationText;
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "纬度:" + lat + "\n经度:" + lng;
} else {
latLongString = "无法获取地理信息";
}
Toast.makeText(SearchXiaoQuActivity.this, latLongString,
Toast.LENGTH_LONG).show();
}
标签:
原文地址:http://my.oschina.net/u/2444750/blog/502489