DeviceCountryProvider.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #if UNITY_IOS
  2. using System.Runtime.InteropServices;
  3. #endif
  4. #if UNITY_ANDROID
  5. using UnityEngine;
  6. #endif
  7. namespace Google.Maps.Scripts {
  8. /// <summary>
  9. /// Script to get the country portion of the device's locale using native code on Android and iOS.
  10. /// </summary>
  11. public class DeviceCountryProvider : CountryProvider {
  12. /// <summary>Device's country code, populated during <see cref="Awake"/>.</summary>
  13. private string CountryCode;
  14. /// <summary>
  15. /// When woken up by Unity, get the device's country code, if available. Do this once at the
  16. /// start, instead of in <see cref="GetCountry"/>, because native calls can be expensive on some
  17. /// platforms.
  18. /// </summary>
  19. public void Awake() {
  20. #if UNITY_EDITOR
  21. // If running in the editor, don't try to run native code, even if the build target is one of
  22. // the mobile platforms below.
  23. CountryCode = null;
  24. #elif UNITY_ANDROID
  25. try {
  26. using (var localeClass = new AndroidJavaClass("java.util.Locale")) {
  27. using (var defaultLocale = localeClass.CallStatic<AndroidJavaObject>("getDefault")) {
  28. CountryCode = defaultLocale.Call<string>("getCountry");
  29. }
  30. }
  31. } catch (System.Exception e) {
  32. Debug.LogWarningFormat("<color=red><b>[Maps SDK]</b></color> DeviceCountryError: " +
  33. "Couldn't get device country: {0}\nSee https://developers.google.com/maps/" +
  34. "documentation/gaming/support/error_codes#device-country-error for more information.",
  35. e);
  36. }
  37. #elif UNITY_IOS
  38. CountryCode = MuskGetLocaleRegion();
  39. #else
  40. CountryCode = null;
  41. #endif
  42. }
  43. /// <inheritdoc/>
  44. public override string GetCountry() {
  45. return CountryCode;
  46. }
  47. #if UNITY_IOS
  48. /// <summary>
  49. /// Native iOS function to get the device region.
  50. /// </summary>
  51. [DllImport("__Internal")]
  52. private static extern string MuskGetLocaleRegion();
  53. #endif
  54. }
  55. }