AndroidBuildPreProcessor.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. #if UNITY_ANDROID
  2. #if UNITY_2022 || UNITY_2021_3_58 || UNITY_2021_3_57 || UNITY_2021_3_56 || UNITY_2021_3_55 || UNITY_2021_3_54 || UNITY_2021_3_53 || UNITY_2021_3_52 || UNITY_2021_3_51 || UNITY_2021_3_50 || UNITY_2021_3_49 || UNITY_2021_3_48 || UNITY_2021_3_47 || UNITY_2021_3_46 || UNITY_2021_3_45 || UNITY_2021_3_44 || UNITY_2021_3_43 || UNITY_2021_3_42 || UNITY_2021_3_41
  3. // 2021.3.41f1+ Gradle version 7.5.1+
  4. // https://docs.unity3d.com/2021.3/Documentation/Manual/android-gradle-overview.html
  5. #define ANDROID_GRADLE_BUILD_JETIFIER_ENTRY_ENABLED
  6. #endif
  7. #if UNITY_6000_0_OR_NEWER || UNITY_2023 || ANDROID_GRADLE_BUILD_JETIFIER_ENTRY_ENABLED
  8. #define ANDROID_GRADLE_BUILD_PRE_PROCESSOR_ENABLED
  9. #endif
  10. using System;
  11. using System.Text.RegularExpressions;
  12. using UnityEngine;
  13. using UnityEditor;
  14. using System.IO;
  15. using GooglePlayServices;
  16. using UnityEditor.Build;
  17. using UnityEditor.Build.Reporting;
  18. namespace GoogleMobileAds.Editor
  19. {
  20. /// <summary>
  21. /// This script will verify and configure your Android build settings to be compatible
  22. /// with the Google Mobile Ads SDK. This includes:
  23. /// - Verify the Android Google Mobile Ads app ID is set.
  24. /// - Throw an exception if the Android Google Mobile Ads app ID is not set.
  25. /// - Set minimum API level to 23 (the target API level may be automatically set, we should not
  26. /// hardcode it).
  27. /// - Enable Custom Main Gradle Template.
  28. /// - Update Custom Main Gradle Template with dependencies using the Play Services Resolver.
  29. /// - Enable Custom Gradle Properties Template.
  30. /// - Update Custom Gradle Properties Template with the Jetifier Ignorelist.
  31. /// </summary>
  32. public class AndroidBuildPreProcessor : IPreprocessBuildWithReport
  33. {
  34. private const string NextGenLibrary = "com.google.android.libraries.ads.mobile.sdk:ads-mobile-sdk";
  35. private const string CurrentLibrary = "com.google.android.gms:play-services-ads";
  36. private const string LatestNextGenVersion = "1.4.0";
  37. private const string CurrentVersion = "25.4.0";
  38. private const string NextGenSpec = NextGenLibrary + ":" + LatestNextGenVersion;
  39. private const string CurrentSpec = CurrentLibrary + ":" + CurrentVersion;
  40. private static readonly string NextGenRegex = Regex.Escape(NextGenLibrary) + @":[\d\.]+[-a-zA-Z0-9]*";
  41. private static readonly string CurrentRegex = Regex.Escape(CurrentLibrary) + @":[\d\.]+[-a-zA-Z0-9]*";
  42. const int StandardMinimumAPILevel = 23;
  43. const int NextGenMinimumAPILevel = 24;
  44. const string CustomGradlePropertiesTemplatesFileName = "gradleTemplate.properties";
  45. const string CustomMainGradleTemplateFileName = "mainTemplate.gradle";
  46. const string JetifierEntry =
  47. "android.jetifier.ignorelist=annotation-experimental-1.4.0.aar";
  48. // Set the callback order to be before EDM4U.
  49. // https://github.com/googlesamples/unity-jar-resolver/blob/master/source/AndroidResolver/src/PlayServicesPreBuild.cs#L39
  50. public int callbackOrder { get { return -1; } }
  51. public void OnPreprocessBuild(BuildReport report)
  52. {
  53. UpdateGmaDependency();
  54. if(!GoogleMobileAdsSettings.LoadInstance().EnableGradleBuildPreProcessor)
  55. {
  56. return;
  57. }
  58. // For more details see, https://developers.google.com/admob/unity/android
  59. #if ANDROID_GRADLE_BUILD_PRE_PROCESSOR_ENABLED
  60. ApplyBuildSettings(report);
  61. #endif
  62. }
  63. private void ApplyBuildSettings(BuildReport report)
  64. {
  65. Debug.Log("Running Android Gradle Build Pre-Processor.");
  66. var sdk = GoogleMobileAdsSettings.LoadInstance().EffectiveGmaAndroidSdk;
  67. int targetMinApi = (sdk == GoogleMobileAdsSettings.GmaAndroidSdk.NextGen)
  68. ? NextGenMinimumAPILevel
  69. : StandardMinimumAPILevel;
  70. if (PlayerSettings.Android.minSdkVersion < (AndroidSdkVersions)targetMinApi)
  71. {
  72. PlayerSettings.Android.minSdkVersion = (AndroidSdkVersions)targetMinApi;
  73. Debug.Log($"Set minimum API Level to: {targetMinApi}.");
  74. }
  75. else
  76. {
  77. Debug.Log($"Verified Minimum API Level is >= {targetMinApi}.");
  78. }
  79. // Create Assets/Plugins folder.
  80. if (!AssetDatabase.IsValidFolder(Path.Combine("Assets", "Plugins")))
  81. {
  82. AssetDatabase.CreateFolder("Assets", "Plugins");
  83. AssetDatabase.Refresh();
  84. }
  85. // Create Assets/Plugins/Android folder.
  86. if (!AssetDatabase.IsValidFolder(Path.Combine("Assets", "Plugins", "Android")))
  87. {
  88. AssetDatabase.CreateFolder(Path.Combine("Assets", "Plugins"), "Android");
  89. AssetDatabase.Refresh();
  90. }
  91. // Ensure Custom Main Gradle Template.
  92. EnsureGradleFileExists(CustomMainGradleTemplateFileName);
  93. // Ensure Custom Gradle Properties Templates.
  94. EnsureGradleFileExists(CustomGradlePropertiesTemplatesFileName);
  95. #if ANDROID_GRADLE_BUILD_JETIFIER_ENTRY_ENABLED
  96. string customGradlePropertiesTemplatesFilePath = Path.Combine(
  97. Application.dataPath,
  98. "Plugins", "Android",
  99. CustomGradlePropertiesTemplatesFileName);
  100. if (File.Exists(customGradlePropertiesTemplatesFilePath))
  101. {
  102. var gradlePropertiesFileContent =
  103. File.ReadAllText(customGradlePropertiesTemplatesFilePath);
  104. if (!gradlePropertiesFileContent.Contains(JetifierEntry))
  105. {
  106. File.AppendAllText(
  107. customGradlePropertiesTemplatesFilePath,
  108. Environment.NewLine + JetifierEntry);
  109. Debug.Log($"Added Jetifier Entry.");
  110. }
  111. else
  112. {
  113. Debug.Log($"Verified Jetifier Entry exists.");
  114. }
  115. }
  116. else
  117. {
  118. Debug.LogError("Failed to add Jetifier Entry.");
  119. }
  120. #endif
  121. Debug.Log("Resolving Android Gradle dependencies.");
  122. PlayServicesResolver.ResolveSync(true);
  123. Debug.Log("Android Build Pre-Processor finished.");
  124. }
  125. /// <summary>
  126. /// Ensures that the given Gradle file exists.
  127. /// </summary>
  128. /// <param name="fileName">name of the given Gradle file.</param>
  129. private void EnsureGradleFileExists(string fileName)
  130. {
  131. bool foundTargetFile = false;
  132. bool foundDisabledFile = false;
  133. // Check for target file.
  134. string targetPath = Path.Combine(Application.dataPath, "Plugins", "Android", fileName);
  135. if (File.Exists(targetPath))
  136. {
  137. foundTargetFile = true;
  138. }
  139. // Check for the ".DISABLED" file.
  140. string disabledPath = Path.Combine(Application.dataPath, "Plugins", "Android",
  141. $"{fileName}.DISABLED");
  142. if (File.Exists(disabledPath))
  143. {
  144. foundDisabledFile = true;
  145. }
  146. // If DISABLED and target exist, delete DISABLED.
  147. if (foundTargetFile && foundDisabledFile)
  148. {
  149. File.Delete(disabledPath);
  150. Debug.Log($"Removed disabled {fileName}.");
  151. return;
  152. }
  153. // If DISABLED exists, move it to target.
  154. if (foundDisabledFile)
  155. {
  156. File.Move(disabledPath, targetPath);
  157. AssetDatabase.Refresh();
  158. Debug.Log($"Enabled {fileName}.");
  159. return;
  160. }
  161. // If target exists, return true.
  162. if (foundTargetFile)
  163. {
  164. Debug.Log($"Verified {fileName}.");
  165. return;
  166. }
  167. // If target does not exist, create it from source.
  168. var unityGradleTemplateDirectory = Path.Combine(
  169. PlayServicesResolver.AndroidPlaybackEngineDirectory,
  170. "Tools",
  171. "GradleTemplates");
  172. string sourceFileName = Path.Combine(unityGradleTemplateDirectory, fileName);
  173. if (!File.Exists(sourceFileName))
  174. {
  175. throw new BuildFailedException(
  176. "Android Build Pre-Processor failed. "+
  177. $"Unable to find source {sourceFileName}. Is your file system read-only?" +
  178. "If this issue persists, contact Google Mobile Ads Support "+
  179. "at https://developers.google.com/admob/support");
  180. }
  181. File.Copy(sourceFileName, targetPath);
  182. AssetDatabase.Refresh();
  183. Debug.Log($"Created {fileName}.");
  184. }
  185. /// <summary>
  186. /// Updates the GoogleMobileAdsDependencies.xml file with the selected SDK dependency.
  187. /// If the file is changed, the EDM4U will be triggered to resolve the dependencies.
  188. /// </summary>
  189. private void UpdateGmaDependency()
  190. {
  191. string desiredSpec = (GoogleMobileAdsSettings.LoadInstance().EffectiveGmaAndroidSdk ==
  192. GoogleMobileAdsSettings.GmaAndroidSdk.NextGen)
  193. ? NextGenSpec
  194. : CurrentSpec;
  195. var pathUtils = ScriptableObject.CreateInstance<EditorPathUtils>();
  196. string directoryPath = pathUtils.GetDirectoryAssetPath();
  197. string dependenciesFilePath =
  198. Path.Combine(directoryPath, "GoogleMobileAdsDependencies.xml");
  199. if (!File.Exists(dependenciesFilePath))
  200. {
  201. Debug.LogError($"GoogleMobileAdsDependencies.xml not found at {dependenciesFilePath}");
  202. return;
  203. }
  204. string fileContent = File.ReadAllText(dependenciesFilePath);
  205. string newContent = fileContent;
  206. if (Regex.IsMatch(fileContent, NextGenRegex))
  207. {
  208. newContent = Regex.Replace(fileContent, NextGenRegex, desiredSpec);
  209. }
  210. else if (Regex.IsMatch(fileContent, CurrentRegex))
  211. {
  212. newContent = Regex.Replace(fileContent, CurrentRegex, desiredSpec);
  213. }
  214. else
  215. {
  216. Debug.LogWarning(
  217. "Could not find existing Google Mobile Ads SDK dependency in " +
  218. "GoogleMobileAdsDependencies.xml to replace.");
  219. }
  220. if (newContent != fileContent)
  221. {
  222. Debug.Log($"Updating GoogleMobileAdsDependencies.xml with {desiredSpec}");
  223. File.WriteAllText(dependenciesFilePath, newContent);
  224. AssetDatabase.Refresh();
  225. PlayServicesResolver.ResolveSync(true);
  226. }
  227. }
  228. }
  229. }
  230. #endif