当前位置:操作系统 > 安卓/Android >>

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

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; 
    } 

补充:移动开发 , Android ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,