简体   繁体   中英

Getting current country name

I'm trying to get the country name where the phone is in. For instance if the user is in Germany it has to say Germany. I've tried several things to make this happen, but I haven't found any proper solution. I know I can use TelephonyManager , but that will give me the ISO, and I want the name of the country. I've also tried this getApplicationContext().getResources().getConfiguration().locale.getDisplayCountry(); , but that always gives me "United States" even though I'm not there. I know this is possible as I've seen it in another application. Should I use the ISO somehow to accomplish what I what, or is there a smarter/easier way?

Please, don't vote this post as duplicate as I've already searched here on Stackoverflow, but there isn't any solution to get the name of the country :)

Where am I? - Get country gives this code

/**
 * 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 static 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM