@@ -5,14 +5,44 @@ import android.telephony.TelephonyManager
55import com.getcode.model.CurrencyCode
66import com.getcode.model.CurrencyCode.Companion
77import com.getcode.model.RegionCode
8+ import kotlinx.coroutines.Dispatchers
9+ import kotlinx.coroutines.withContext
10+ import okhttp3.OkHttpClient
11+ import okhttp3.Request
12+ import org.json.JSONObject
813import java.util.*
14+ import java.util.concurrent.TimeUnit
915
1016object LocaleUtils {
11- fun getDefaultCountry (context : Context ): String {
17+ suspend fun getDefaultCountry (context : Context ): String? {
1218 val tm = context.getSystemService(Context .TELEPHONY_SERVICE ) as TelephonyManager
1319 val networkCountryIso = tm.networkCountryIso.uppercase()
1420 val simCountryIso = tm.simCountryIso.uppercase()
15- return simCountryIso.ifBlank { networkCountryIso }
21+ val localeCountry = context.resources.configuration.locale.country.uppercase()
22+
23+ val simCountry = if (simCountryIso.isNotBlank() && simCountryIso.length == 2 ) simCountryIso else null
24+ val localeCountryValid = if (localeCountry.isNotBlank() && localeCountry.length == 2 ) localeCountry else null
25+ val networkCountry = if (networkCountryIso.isNotBlank() && networkCountryIso.length == 2 ) networkCountryIso else null
26+
27+ return simCountry ? : localeCountryValid ? : networkCountry ? : getCountryFromIp()
28+ }
29+
30+ private suspend fun getCountryFromIp (): String? = withContext(Dispatchers .IO ) {
31+ try {
32+ val client = OkHttpClient .Builder ()
33+ .connectTimeout(5 , TimeUnit .SECONDS )
34+ .readTimeout(5 , TimeUnit .SECONDS )
35+ .build()
36+ val request = Request .Builder ().url(" http://ip-api.com/json/?fields=countryCode" ).build()
37+ val response = client.newCall(request).execute()
38+ if (response.isSuccessful) {
39+ val json = JSONObject (response.body?.string() ? : " {}" )
40+ val ipCountry = json.optString(" countryCode" , " " ).uppercase()
41+ if (ipCountry.length == 2 ) ipCountry else " US"
42+ } else null
43+ } catch (e: Exception ) {
44+ return @withContext null
45+ }
1646 }
1747
1848 fun getDefaultCurrency (context : Context ): String {
0 commit comments