LanguageUtils.java 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. package com.cooleshow.base.utils;
  2. import android.app.Activity;
  3. import android.content.Context;
  4. import android.content.res.Configuration;
  5. import android.content.res.Resources;
  6. import android.os.Build;
  7. import android.text.TextUtils;
  8. import android.util.Log;
  9. import java.util.Locale;
  10. import androidx.annotation.NonNull;
  11. import androidx.annotation.Nullable;
  12. /**
  13. * <pre>
  14. * author: Blankj
  15. * blog : http://blankj.com
  16. * time : 2019/06/20
  17. * desc : utils about language
  18. * </pre>
  19. */
  20. public class LanguageUtils {
  21. private static final String KEY_LOCALE = "KEY_LOCALE";
  22. private static final String VALUE_FOLLOW_SYSTEM = "VALUE_FOLLOW_SYSTEM";
  23. private LanguageUtils() {
  24. throw new UnsupportedOperationException("u can't instantiate me...");
  25. }
  26. /**
  27. * Apply the system language.
  28. */
  29. public static void applySystemLanguage() {
  30. applySystemLanguage(false);
  31. }
  32. /**
  33. * Apply the system language.
  34. *
  35. * @param isRelaunchApp True to relaunch app, false to recreate all activities.
  36. */
  37. public static void applySystemLanguage(final boolean isRelaunchApp) {
  38. applyLanguageReal(null, isRelaunchApp);
  39. }
  40. /**
  41. * Apply the language.
  42. *
  43. * @param locale The language of locale.
  44. */
  45. public static void applyLanguage(@NonNull final Locale locale) {
  46. applyLanguage(locale, false);
  47. }
  48. /**
  49. * Apply the language.
  50. *
  51. * @param locale The language of locale.
  52. * @param isRelaunchApp True to relaunch app, false to recreate all activities.
  53. */
  54. public static void applyLanguage(@NonNull final Locale locale,
  55. final boolean isRelaunchApp) {
  56. applyLanguageReal(locale, isRelaunchApp);
  57. }
  58. private static void applyLanguageReal(final Locale locale,
  59. final boolean isRelaunchApp) {
  60. if (locale == null) {
  61. UtilsBridge.getSpUtils4Utils().put(KEY_LOCALE, VALUE_FOLLOW_SYSTEM, true);
  62. } else {
  63. UtilsBridge.getSpUtils4Utils().put(KEY_LOCALE, locale2String(locale), true);
  64. }
  65. Locale destLocal = locale == null ? getLocal(Resources.getSystem().getConfiguration()) : locale;
  66. updateAppContextLanguage(destLocal, new Utils.Consumer<Boolean>() {
  67. @Override
  68. public void accept(Boolean success) {
  69. if (success) {
  70. restart(isRelaunchApp);
  71. } else {
  72. // use relaunch app
  73. UtilsBridge.relaunchApp();
  74. }
  75. }
  76. });
  77. }
  78. private static void restart(final boolean isRelaunchApp) {
  79. if (isRelaunchApp) {
  80. UtilsBridge.relaunchApp();
  81. } else {
  82. for (Activity activity : UtilsBridge.getActivityList()) {
  83. activity.recreate();
  84. }
  85. }
  86. }
  87. /**
  88. * Return whether applied the language by {@link LanguageUtils}.
  89. *
  90. * @return {@code true}: yes<br>{@code false}: no
  91. */
  92. public static boolean isAppliedLanguage() {
  93. return getAppliedLanguage() != null;
  94. }
  95. /**
  96. * Return whether applied the language by {@link LanguageUtils}.
  97. *
  98. * @param locale The locale.
  99. * @return {@code true}: yes<br>{@code false}: no
  100. */
  101. public static boolean isAppliedLanguage(@NonNull Locale locale) {
  102. Locale appliedLocale = getAppliedLanguage();
  103. if (appliedLocale == null) {
  104. return false;
  105. }
  106. return isSameLocale(locale, appliedLocale);
  107. }
  108. /**
  109. * Return the applied locale.
  110. *
  111. * @return the applied locale
  112. */
  113. public static Locale getAppliedLanguage() {
  114. final String spLocaleStr = UtilsBridge.getSpUtils4Utils().getString(KEY_LOCALE);
  115. if (TextUtils.isEmpty(spLocaleStr) || VALUE_FOLLOW_SYSTEM.equals(spLocaleStr)) {
  116. return null;
  117. }
  118. return string2Locale(spLocaleStr);
  119. }
  120. /**
  121. * Return the locale of context.
  122. *
  123. * @return the locale of context
  124. */
  125. public static Locale getContextLanguage(Context context) {
  126. return getLocal(context.getResources().getConfiguration());
  127. }
  128. /**
  129. * Return the locale of applicationContext.
  130. *
  131. * @return the locale of applicationContext
  132. */
  133. public static Locale getAppContextLanguage() {
  134. return getContextLanguage(Utils.getApp());
  135. }
  136. /**
  137. * Return the locale of system
  138. *
  139. * @return the locale of system
  140. */
  141. public static Locale getSystemLanguage() {
  142. return getLocal(Resources.getSystem().getConfiguration());
  143. }
  144. /**
  145. * Update the locale of applicationContext.
  146. *
  147. * @param destLocale The dest locale.
  148. * @param consumer The consumer.
  149. */
  150. public static void updateAppContextLanguage(@NonNull Locale destLocale, @Nullable Utils.Consumer<Boolean> consumer) {
  151. pollCheckAppContextLocal(destLocale, 0, consumer);
  152. }
  153. static void pollCheckAppContextLocal(final Locale destLocale, final int index, final Utils.Consumer<Boolean> consumer) {
  154. Resources appResources = Utils.getApp().getResources();
  155. Configuration appConfig = appResources.getConfiguration();
  156. Locale appLocal = getLocal(appConfig);
  157. setLocal(appConfig, destLocale);
  158. Utils.getApp().getResources().updateConfiguration(appConfig, appResources.getDisplayMetrics());
  159. if (consumer == null) return;
  160. if (isSameLocale(appLocal, destLocale)) {
  161. consumer.accept(true);
  162. } else {
  163. if (index < 20) {
  164. UtilsBridge.runOnUiThreadDelayed(new Runnable() {
  165. @Override
  166. public void run() {
  167. pollCheckAppContextLocal(destLocale, index + 1, consumer);
  168. }
  169. }, 16);
  170. return;
  171. }
  172. Log.e("LanguageUtils", "appLocal didn't update.");
  173. consumer.accept(false);
  174. }
  175. }
  176. /**
  177. * If applyLanguage not work, try to call it in {@link Activity#attachBaseContext(Context)}.
  178. *
  179. * @param context The baseContext.
  180. * @return the context with language
  181. */
  182. public static Context attachBaseContext(Context context) {
  183. String spLocaleStr = UtilsBridge.getSpUtils4Utils().getString(KEY_LOCALE);
  184. if (TextUtils.isEmpty(spLocaleStr) || VALUE_FOLLOW_SYSTEM.equals(spLocaleStr)) {
  185. return context;
  186. }
  187. Locale settingsLocale = string2Locale(spLocaleStr);
  188. if (settingsLocale == null) return context;
  189. Resources resources = context.getResources();
  190. Configuration config = resources.getConfiguration();
  191. setLocal(config, settingsLocale);
  192. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
  193. return context.createConfigurationContext(config);
  194. } else {
  195. resources.updateConfiguration(config, resources.getDisplayMetrics());
  196. return context;
  197. }
  198. }
  199. static void applyLanguage(final Activity activity) {
  200. String spLocale = UtilsBridge.getSpUtils4Utils().getString(KEY_LOCALE);
  201. if (TextUtils.isEmpty(spLocale)) {
  202. return;
  203. }
  204. Locale destLocal;
  205. if (VALUE_FOLLOW_SYSTEM.equals(spLocale)) {
  206. destLocal = getLocal(Resources.getSystem().getConfiguration());
  207. } else {
  208. destLocal = string2Locale(spLocale);
  209. }
  210. if (destLocal == null) return;
  211. updateConfiguration(activity, destLocal);
  212. updateConfiguration(Utils.getApp(), destLocal);
  213. }
  214. private static void updateConfiguration(Context context, Locale destLocal) {
  215. Resources resources = context.getResources();
  216. Configuration config = resources.getConfiguration();
  217. setLocal(config, destLocal);
  218. resources.updateConfiguration(config, resources.getDisplayMetrics());
  219. }
  220. private static String locale2String(Locale locale) {
  221. String localLanguage = locale.getLanguage(); // this may be empty
  222. String localCountry = locale.getCountry(); // this may be empty
  223. return localLanguage + "$" + localCountry;
  224. }
  225. private static Locale string2Locale(String str) {
  226. Locale locale = string2LocaleReal(str);
  227. if (locale == null) {
  228. Log.e("LanguageUtils", "The string of " + str + " is not in the correct format.");
  229. UtilsBridge.getSpUtils4Utils().remove(KEY_LOCALE);
  230. }
  231. return locale;
  232. }
  233. private static Locale string2LocaleReal(String str) {
  234. if (!isRightFormatLocalStr(str)) {
  235. return null;
  236. }
  237. try {
  238. int splitIndex = str.indexOf("$");
  239. return new Locale(str.substring(0, splitIndex), str.substring(splitIndex + 1));
  240. } catch (Exception ignore) {
  241. return null;
  242. }
  243. }
  244. private static boolean isRightFormatLocalStr(String localStr) {
  245. char[] chars = localStr.toCharArray();
  246. int count = 0;
  247. for (char c : chars) {
  248. if (c == '$') {
  249. if (count >= 1) {
  250. return false;
  251. }
  252. ++count;
  253. }
  254. }
  255. return count == 1;
  256. }
  257. private static boolean isSameLocale(Locale l0, Locale l1) {
  258. return UtilsBridge.equals(l1.getLanguage(), l0.getLanguage())
  259. && UtilsBridge.equals(l1.getCountry(), l0.getCountry());
  260. }
  261. private static Locale getLocal(Configuration configuration) {
  262. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
  263. return configuration.getLocales().get(0);
  264. } else {
  265. return configuration.locale;
  266. }
  267. }
  268. private static void setLocal(Configuration configuration, Locale locale) {
  269. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
  270. configuration.setLocale(locale);
  271. } else {
  272. configuration.locale = locale;
  273. }
  274. }
  275. }