Locale.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #include "il2cpp-config.h"
  2. #if IL2CPP_TARGET_ANDROID
  3. #include <string>
  4. #include <android/log.h>
  5. #include <jni.h>
  6. extern JavaVM *sJavaVM;
  7. namespace il2cpp
  8. {
  9. namespace os
  10. {
  11. std::string AndroidGetLocale()
  12. {
  13. std::string locale;
  14. if (sJavaVM == nullptr)
  15. {
  16. __android_log_print(ANDROID_LOG_INFO, "IL2CPP", "Java VM not initialized");
  17. return locale;
  18. }
  19. JNIEnv* env = nullptr;
  20. bool detached = sJavaVM->GetEnv((void**)&env, JNI_VERSION_1_2) == JNI_EDETACHED;
  21. if (detached)
  22. {
  23. sJavaVM->AttachCurrentThread(&env, NULL);
  24. }
  25. jclass localeClass = env->FindClass("java/util/Locale");
  26. if (localeClass != nullptr)
  27. {
  28. jmethodID getDefault = env->GetStaticMethodID(localeClass, "getDefault", "()Ljava/util/Locale;");
  29. if (getDefault != nullptr)
  30. {
  31. jobject def = env->CallStaticObjectMethod(localeClass, getDefault);
  32. jmethodID toLanguageTag = env->GetMethodID(localeClass, "toLanguageTag", "()Ljava/lang/String;");
  33. // toLanguageTag is available since API 21 only, so returning default locale for Android 4.4
  34. if (toLanguageTag != nullptr)
  35. {
  36. jstring tag = (jstring)env->CallObjectMethod(def, toLanguageTag);
  37. const char *nativeTag = env->GetStringUTFChars(tag, nullptr);
  38. __android_log_print(ANDROID_LOG_INFO, "IL2CPP", "Locale %s", nativeTag);
  39. locale = nativeTag;
  40. env->ReleaseStringUTFChars(tag, nativeTag);
  41. }
  42. }
  43. }
  44. if (env->ExceptionCheck())
  45. {
  46. env->ExceptionClear();
  47. }
  48. if (detached)
  49. sJavaVM->DetachCurrentThread();
  50. return locale;
  51. }
  52. } /* namespace os */
  53. } /* namespace il2cpp */
  54. #endif