LibreTube/app/src/main/java/com/github/libretube/util/LocaleHelper.kt

91 lines
2.6 KiB
Kotlin
Raw Normal View History

2022-06-07 13:05:49 +05:30
package com.github.libretube.util
import android.content.Context
import android.os.Build
2022-07-08 02:00:47 +05:30
import android.telephony.TelephonyManager
2022-09-08 21:59:00 +05:30
import com.github.libretube.constants.PreferenceKeys
2022-06-07 13:05:49 +05:30
import java.util.*
2022-06-26 15:56:19 +05:30
object LocaleHelper {
2022-06-07 13:05:49 +05:30
fun updateLanguage(context: Context) {
2022-07-17 21:48:39 +05:30
val languageName = PreferenceHelper.getString(PreferenceKeys.LANGUAGE, "sys")
2022-08-24 21:26:57 +05:30
if (languageName == "sys") {
updateLocaleConf(context, Locale.getDefault())
2022-08-27 18:43:24 +05:30
} else if (languageName.contains("-") == true) {
2022-07-20 01:26:17 +05:30
val languageParts = languageName.split("-")
2022-07-06 19:43:51 +05:30
val locale = Locale(
2022-07-20 01:26:17 +05:30
languageParts[0],
languageParts[1]
2022-07-06 19:43:51 +05:30
)
updateLocaleConf(context, locale)
2022-07-20 01:26:17 +05:30
} else {
val locale = Locale(languageName.toString())
updateLocaleConf(context, locale)
2022-06-07 13:05:49 +05:30
}
}
2022-07-06 19:43:51 +05:30
private fun updateLocaleConf(context: Context, locale: Locale) {
2022-06-07 13:05:49 +05:30
// Change API Language
Locale.setDefault(locale)
// Change App Language
val res = context.resources
val dm = res.displayMetrics
val conf = res.configuration
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
conf.setLocale(locale)
} else {
conf.locale = locale
}
res.updateConfiguration(conf, dm)
}
2022-07-08 02:00:47 +05:30
fun getDetectedCountry(context: Context, defaultCountryIsoCode: String): String {
detectSIMCountry(context)?.let {
return it
}
detectNetworkCountry(context)?.let {
return it
}
detectLocaleCountry(context)?.let {
return it
}
return defaultCountryIsoCode
}
private fun detectSIMCountry(context: Context): String? {
try {
2022-07-08 22:20:11 +05:30
val telephonyManager =
context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
2022-07-08 02:00:47 +05:30
return telephonyManager.simCountryIso
} catch (e: Exception) {
e.printStackTrace()
}
return null
}
private fun detectNetworkCountry(context: Context): String? {
try {
2022-07-08 22:20:11 +05:30
val telephonyManager =
context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
2022-07-08 02:00:47 +05:30
return telephonyManager.networkCountryIso
} catch (e: Exception) {
e.printStackTrace()
}
return null
}
private fun detectLocaleCountry(context: Context): String? {
try {
return context.resources.configuration.locales[0].country
} catch (e: Exception) {
e.printStackTrace()
}
return null
}
2022-06-07 13:05:49 +05:30
}