获取Android当前的国家/地区

时间:2014-02-17 07:30:43

标签: android geolocation location geocoding country

我正在创建一个应用,在其中我为每个国家/地区分配不同的值,并根据该值执行某些操作。像:

Argentina 3
Australia 7
USA 23

要选择国家/地区,我需要使用用户的当前国家/地区,因为我正在使用Google的地理编码器:

geocoder.getFromLocation

Geocoder documentation

但如果我有很多用户(希望如此),那将是一个问题,因为API 使用限制为2500(有/无API密钥:每24小时2,500个请求。)
Geocoder API Limits

问题1:关于使用限制,该数字是使用我的地图的所有用户的最大请求数量吗?

编辑:我发现了这个

  

由于地理编码限制是按用户会话进行的,因此不存在您的风险   随着用户群的增长,应用程序将达到全局限制。   客户端地理编码不会面临配额限制,除非您执行   用户会话中的批量地理编码请求。因此,跑步   客户端地理编码,您通常不必担心您的   配额。   usage Limits

问题2:假设我使用Geocoder.getFromLocation(),是否有Google使用的国家/地区名称列表?例如,他们可能有“美国”,“美国”或“美国”,甚至“美利坚合众国”。我需要这是为了访问上表中的国家/地区值。

我正在考虑最初使用典型的方式获取国家:

telephonyManager.getSimCountryIso();

context.getResources().getConfiguration().locale.getCountry(); 

并添加刷新按钮,以便用户在旅行使用地理编码器)时进行更新。

问题3 :您还有其他建议吗?替代?

3 个答案:

答案 0 :(得分:3)

对于#2-国家代码。这是ISO标准。这将是2个字母的代码。该列表可在此处找到http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2

答案 1 :(得分:1)

新答案承诺给fersarr一个新的解决方案,这适用于GPS和谷歌地图API,也不是我最好的代码,但

private GeoPoint getLocation() {
try {
    LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String provider = locationManager.getBestProvider(criteria,true);
//In order to make sure the device is getting the location, request updates.
// this requests updates every hour or if the user moves 1 kilometer
Location curLocation = locationManager.getLastKnownLocation(provider);
GeoPoint curGeoPoint = new GeoPoint((int)(curLocation.getLatitude() * 1e6), (int)(curLocation.getLongitude()*1e6));
return curGeoPoint;
} catch (NullPointerException e) {
    Log.e("your app name here","Log your error here");
}
return null;
}


public static String getCountryName(Context context, GeoPoint curLocal) {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses = null;
try {
    addresses = geocoder.getFromLocation((double)curLocal.getLatitudeE6() / 1e6,(double)curLocal.getLongitudeE6()/ 1e6,1);
} catch (IOException ignored) {
    Address result;
    if (addresses != null && !addresses.isEmpty()) {
        return addresses.get(0).getCountryName();
    }
    return null;
}
return addresses.get(0).getCountryCode();
}

您需要在此代码中进行一些清理,因为这是在运行中没有清理代码。但是这样做,第一种方法是getLocation将从GPS中提取你当前的Geo点(如果你不能在设备上使用GPS系统这将无效)那么你可以将geopoint和context(你的活动)传递给应该返回国家/地区名称的getCountryName(在我的情况下,它也是美国),它会返回一个列表,您可能需要处理更多的列表,然后回到有争议地点的国家/地区代码。

答案 2 :(得分:0)

我做了一个快速的Google搜索并找到了 Where am I? - Get country

基本上如果你打电话

String locale = getResources().getConfiguration().locale.getCountry();
Log.d("IssuesEtc","the local is " + locale);

它应该给你国家代码。我跑了上面的片段,然后我回来了     当地是美国 所以它似乎在我的手机上工作(三星S大火,cyagin mod,在T-Mobile上) 我还应该注意,调用是在一个扩展Activity的类中完成的,如果你在一个类中有一个在其上存在上下文的类,你将需要获取上下文来运行getResources()方法。

相关问题