AndroidUtilCode icon indicating copy to clipboard operation
AndroidUtilCode copied to clipboard

LanguageUtils.updateAppContextLanguage更新无效 提供临时解决方案 等待auc更新

Open liangrk opened this issue 3 years ago • 4 comments

描述 Bug

简洁地描述下 Bug。

  • AndroidUtilCode 的版本:1.31.6
  • 出现 Bug 的设备型号:华为/荣耀/小米/原生模拟器,
  • 设备的 Android 版本:7.0/10/11

相关代码

LanguageUtils.applyLanguage 应用指定语言后, 重启后 application context 语言没有更新 LanguageUtils.updateAppContextLanguage 加上后也没有效果

问题:

应用完后 直接杀掉应用重启 会出现部分文案没有应用指定语言的翻译

初步排查: 该类型文案是StringUtils.getString直接获取. 如果采用当前Activity context即没有该问题 尝试调用 LanguageUtils.updateAppContextLanguage 方法去更新, 依旧不行.

临时的解决方案思路

获取 auc 对应语言的字符, 转为local 在 application-attachBaseContext 中手动更新 context 内部的语言.

fun obtainCacheLocalWithAUC(context: Context?): String {
    if (context == null) return ""
    if (innerSp == null) {
        // 采用auc中的历史配置name
        innerSp = context.getSharedPreferences("Utils", Context.MODE_PRIVATE)
    }
    //查auc中存的配置
    return innerSp?.getString("KEY_LOCALE", "") ?: ""
}

fun convertCoutry2LocalWithAUC(str: String): Locale? {
    return if (!isRightFormatLocalStr(str)) {   // 该方法为auc中的, 自己去拿即可
        null
    } else try {
        val splitIndex = str.indexOf("$")
        Locale(str.substring(0, splitIndex), str.substring(splitIndex + 1))
    } catch (ignore: Exception) {
        null
    }
}

// application
override fun attachBaseContext(base: Context?) {
      kotlin.runCatching {
          val localCoutry = AppLanguageKit.obtainCacheLocalWithAUC(base)
          val locale = AppLanguageKit.convertCounty2LocalWithAUC(localCoutry )
          val context = if (base != null && locale != null) {
              val resource = base.resources
              val conf = resource.configuration

              conf.setLocale(locale)
              conf.setLayoutDirection(locale)
              base.createConfigurationContext(conf)
          } else {
              base
          }
          super.attachBaseContext(context)
      }.onFailure {
          it.printStackTrace()
          super.attachBaseContext(base)
      }
  }


liangrk avatar Sep 24 '22 15:09 liangrk

可以帮提 bug 哈

Blankj avatar Oct 14 '22 16:10 Blankj