How to determine an Android device's current country location regardless of user location settings?
Asked Answered
W

2

8

I need to determine the country (iso3) the device is in even if the user's device has GPS turned off and does not allow apps to access it's location.

I also need to account for tablets that have no sim card and thus cannot use telephonyManager.

For this reason I don't believe I can use the location manager (also because of these reasons: LocationManager requestLocationUpdates doesn't work)

The approach I am thinking I will need is to make a simple HTTP request to a third party ip location api: e.g. http://www.ipinfodb.com/ip_location_api.php or https://freegeoip.net

Is this the best way to do it? What is the best open api to use?

Warnock answered 6/3, 2015 at 20:21 Comment(1)
Keep VPNs and corporate networks in mind. A certain corporate network resulted in me being geolocated me to Taiwan when I'm in India. Your users would be pissed if they are licensed to use your app in India but your app pops up a dialog saying "Sorry, Taiwan is not supported."Mortal
M
9

Your approach of third party ip location api seems right to currently. May be This would help you

http://ip-api.com/docs/api:json

http://ip-api.com/json

Mcgaha answered 6/3, 2015 at 20:37 Comment(3)
That service seems to work great, but what service is this? There is no information about the rules of the service.Warnock
As per my R&D and excprience their is nonMcgaha
I will mark this as correct because though I am not using the service mentioned above, I did decide on a custom api endpoint that we built to answer this question rather than rely on the device.Warnock
A
4

You can use the TelephonyManager

TelephonyManager tm = (TelephonyManager)this.getSystemService(this.TELEPHONY_SERVICE);
String countryCode = tm.getNetworkCountryIso();

Update: Since you cannot use telephony I would suggest trying this, as it get's the users input from when they setup the device.

String locale = context.getResources().getConfiguration().locale.getCountry();
Alcaide answered 6/3, 2015 at 20:24 Comment(5)
Tablets without sim cards will not have a TelephonyManager so I cannot rely on that. I have updated my question to include that. ThanksWarnock
That's an interesting idea. I haven't tried, but is that spoofable? I could not rely on something that a user could set ad hoc.Warnock
I'm not sure, can I ask what you will use this for?Alcaide
The app has licensing requirements that only allow certain features in a subset of countries. So we need to know for sure what country the user is in as they are using the app.Warnock
Hmm alright, you can use the TelephonyManager and/or the getCountry() and if one of those doesn't work or is null you can check the location of the IP address by using an outside library.Alcaide

© 2022 - 2024 — McMap. All rights reserved.