views:

97

answers:

4

An android mobile actually does know quite well where it is - but is there a way of retrieving the country by something like a country code?

No need of knowing the exact GPS position - the country is sufficient

I first thought of using the time zone, but actually I need more information than that since it makes a difference if the location is New York or Lima.

The background of the question: I have an application that uses temperature values, and I'd like to set the default unit either to Celsius or Fahrenheit, depending on whether the location is US or outside

+1  A: 

First, get the LocationManager. Then, call LocationManager.getLastKnownPosition. Then, create a GeoCoder and call GeoCoder.getFromLocation. Do this is a separate thread!! This will give you a list of Address objects. Call Address.getCountryName and you got it.

Keep in mind that the last known position can be a stale, so if the user just crossed the border, you may not know about it for a while.

EboMike
For this application changing the default unit would not be desired when moving countries as the user's preference of Celsius or Fahrenheit will not change as he ventures to new lands.
stealthcopter
+1  A: 

You could use getNetworkCountryIso() from TelephonyManager to get the country the phone is currently in (although apparently this is unreliable on CDMA networks).

Dave Webb
that sounds pretty straight forward and worked well at the emulator in first instance - could you just explain why it's unreliable on CDMA networks?
Martin
ah okay, I got it - because the documentation says so :)
Martin
Because of the application this wouldn't be the best solution as when a user travels abroad their default unit would change. It would make more sense to have a static default unit based on the phones locale settings, which then can of course be changed in a setting somewhere.
stealthcopter
+5  A: 

This will get the country code:

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

can also replace getCountry() with getISO3Country() to get a 3 letter ISO code for the country. This will get the country name:

 String locale = context.getResources().getConfiguration().locale.getDisplayCountry();

This seems easier than the other methods and rely upon the localisation settings on the phone, so if a US user is abroad they probably still want Fahrenheit and this will work :)

stealthcopter
I totally agree on this.
Andrejs Cainikovs
+1  A: 

Actually I just found out that there is even one more way of getting a country code, using the getSimCountryIso() method of TelephoneManager:

TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String countryCode = tm.getSimCountryIso();

Since it is the sim code it also should not change when traveling to other countries.

Martin