搞了大半天的定位,本地不能访问到谷歌网站就是麻烦!!连谷歌地图也不能访问。师姐无意给了个博客,看了之后,发现是用Geocoder 这个,获取到地址信息!!接下来附上源码!!1!
public class AWLocation {
Context context;
String latLongStr;
String addr;
LocationManager locationManager;
Location location;
String provider;
public AWLocation(Context context){
this.context = context;
}
public String setLocate(){
locationManager = (LocationManager)context
.getSystemService(Context.LOCATION_SERVICE);
getProvider();
location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 2000, 10, locationListener);
updateWithNewLocation(location);
return addr;
}
/**
* 构建位置查询条件
*/
private void getProvider(){
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);
}
/**
* Gps消息监听器
*/
private final LocationListener locationListener = new LocationListener(){
// 位置发生改变后调用
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
// provider被用户关闭后调用
public void onProviderDisabled(String provider){
updateWithNewLocation(null);
}
// provider被用户开启后调用
public void onProviderEnabled(String provider){ }
// provider状态变化时调用
public void onStatusChanged(String provider, int status,
Bundle extras){ }
};
/**
* 更新地址信息
* @param location
*/
protected void updateWithNewLocation(Location location) {
if(location != null){
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongStr = "纬度:" + lat +""+ "经度:" + lng;
}
else{
latLongStr = "无法获取地理信息";
}
addr = latLongStr + getAddressbyGeoPoint(location).toString();
}
private List<Address> getAddressbyGeoPoint(Location location) {
List<Address> result = null;
try {
if (location != null) {
// 获取Geocoder,通过Geocoder就可以拿到地址信息
Geocoder gc = new Geocoder(context, Locale.getDefault());
result = gc.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}