Created
May 17, 2017 12:13
-
-
Save Ray33/43356eb18408c3cadbb30dee9be33f45 to your computer and use it in GitHub Desktop.
Get user country by network
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Get ISO 3166-1 alpha-2 country code for this device (or null if not available) | |
* @param context Context reference to get the TelephonyManager instance from | |
* @return country code or null | |
*/ | |
public String getUserCountry(Context context) { | |
try { | |
final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); | |
final String simCountry = tm.getSimCountryIso(); | |
if (simCountry != null && simCountry.length() == 2) { // SIM country code is available | |
return simCountry.toLowerCase(Locale.US); | |
} | |
else if (tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) { // device is not 3G (would be unreliable) | |
String networkCountry = tm.getNetworkCountryIso(); | |
if (networkCountry != null && networkCountry.length() == 2) { // network country code is available | |
return networkCountry.toLowerCase(Locale.US); | |
} | |
} | |
} | |
catch (Exception e) { } | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based on :
http://stackoverflow.com/questions/3659809/where-am-i-get-country