Skip to content

Instantly share code, notes, and snippets.

@Ray33
Created May 17, 2017 12:13
Show Gist options
  • Save Ray33/43356eb18408c3cadbb30dee9be33f45 to your computer and use it in GitHub Desktop.
Save Ray33/43356eb18408c3cadbb30dee9be33f45 to your computer and use it in GitHub Desktop.
Get user country by network
/**
* 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;
}
@Ray33
Copy link
Author

Ray33 commented May 17, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment