当前位置: 代码迷 >> Android >> Android 失去地理位置并分析出具体城市
  详细解决方案

Android 失去地理位置并分析出具体城市

热度:45   发布时间:2016-05-01 18:46:42.0
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;		// 取得效果最好的criteria		String 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;	}
  相关解决方案