Android 得到地理位置并分析出具体城市
/** * 通过GPS得到城市名 * * @param context * 一個Activity * @return 城市名 */public static String getCityName(Context context) {LocationManager locationManager;String contextString = Context.LOCATION_SERVICE;locationManager = (LocationManager) context.getSystemService(contextString);Criteria criteria = new Criteria();criteria.setAccuracy(Criteria.ACCURACY_FINE);criteria.setAltitudeRequired(false);criteria.setBearingRequired(false);criteria.setCostAllowed(false);criteria.setPowerRequirement(Criteria.POWER_LOW);String cityName = null;// 取得效果最好的criteriaString provider = locationManager.getBestProvider(criteria, true);if (provider == null) {return null;}// 得到坐标相关的信息Location location = locationManager.getLastKnownLocation(provider);if (location == null) {return null;}if (location != null) {double latitude = location.getLatitude();double longitude = location.getLongitude();// 更具地理环境来确定编码Geocoder gc = new Geocoder(context, Locale.getDefault());try {// 取得地址相关的一些信息\经度、纬度List<Address> addresses = gc.getFromLocation(latitude, longitude, 1);StringBuilder sb = new StringBuilder();if (addresses.size() > 0) {Address address = addresses.get(0);sb.append(address.getLocality()).append("\n");cityName = sb.toString();}} catch (IOException e) {}}return cityName;}