简体   繁体   中英

Get country code based on user's current location Android

I have already tried out the following code to get country code name

TelephonyManager tm = (TelephonyManager)getActivity().getSystemService(getActivity().TELEPHONY_SERVICE);
        String countryCodeValue = tm.getNetworkCountryIso();

But I guess this does not work if I want to get current country code in which the user is.

For example if user travels from one country to another I want to get the country code in which he is in.

I have a solution to get user's current country code but I am stuck:

  1. I fetch users current location.
  2. Get the user address using its current location from this I can get the country name.

But is there any way I can get the country code from its country name in android ?

Also please let me me know if there is more efficient way.

Thanks :)

您可以通过getResources().getConfiguration().locale.toString().split("_")[1]获得ISO 3166-1 alpha-2(美国,GB等)。

For anyone coming across this question in the future. Use SmartLocation

Kotlin:

SmartLocation.with(this).location(LocationGooglePlayServicesProvider()).oneFix().start {
            SmartLocation.with(this).geocoding().reverse(it, OnReverseGeocodingListener { location, mutableList ->
                val countryCode = mutableList[0].countryCode
            })
        }

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