首页 > 安全资讯 >

Android得到地理位置并分析出具体城市

11-08-17

Java代码/** * 通过GPS得到城市名 * * @param context * 一個Activity * @return 城市名 */ public static String getCityName(Context context) { LocationManager locationManager; Stri...

Java代码 
/**
     * 通过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; 
    } 

相关文章
最新文章
热点推荐