Reliable method to get the country the user is in?

后端 未结 5 918
情话喂你
情话喂你 2020-12-05 03:19

I usually get the country from the device\'s language. It works but now I have to recognize Brazil. And most of the devices only have portuguese (pt_PT), and no portuguese (

相关标签:
5条回答
  • 2020-12-05 03:31

    It's working on me.

    String countryISOCode;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        TelephonyManager teleMgr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
        if (teleMgr != null){
            countryISOCode = teleMgr.getSimCountryIso();
        }
    

    ............................

    0 讨论(0)
  • 2020-12-05 03:37

    You can pull the location from the phone network:

    TelephonyManager.getNetworkCountryIso()
    

    Or from the SIM card:

    TelephonyManager.getSimCountryIso()
    

    Or, if you have the user's phone number, you may be able to match it to the country through this data.

    Ideally, you could use all three of these (in some order, perhaps SIM, Phone #, then Network), and if none works, use reverse geolocation as a last resort.

    0 讨论(0)
  • 2020-12-05 03:43
    TelephonyManager mTelephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    mTelephonyManager.getNetworkCountryIso();
    

    As answered by Eric, the above code is the best approach. It is also worth noting that,

    mTelephonyManager.getSimCountryIso()
    

    should not be used as this would indicate the home country of the SIM provider (E.g. A Vodaphone UK SIM would return "gb", A Vodaphone Germany SIM would return "de") and not the current location (Country) of the device. This difference is significant when the user is roaming.

    0 讨论(0)
  • 2020-12-05 03:49

    Try this:

     TelephonyManager teleMgr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
     if (teleMgr != null){
         countryISOCode = teleMgr.getSimCountryIso();
     }
    

    Now, countryISOCode would contain one of the following similar to the ISO 3166 country codes as per this Wikipedia entry.

    0 讨论(0)
  • 2020-12-05 03:51

    Geolocation would be the most effective and unobtrusive. You could always use geolocation, and if the user has it disabled display your dialog asking for their country. The less you bug the user for information the better.

    0 讨论(0)
提交回复
热议问题