AndroidBuildPreProcessor.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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.Linq;
  12. using System.Reflection;
  13. using System.Runtime.ExceptionServices;
  14. using System.Text.RegularExpressions;
  15. using UnityEngine;
  16. using UnityEditor;
  17. using System.IO;
  18. using UnityEditor.Build;
  19. using UnityEditor.Build.Reporting;
  20. namespace GoogleMobileAds.Editor
  21. {
  22. /// <summary>
  23. /// This script will verify and configure your Android build settings to be compatible
  24. /// with the Google Mobile Ads SDK. This includes:
  25. /// - Verify the Android Google Mobile Ads app ID is set.
  26. /// - Throw an exception if the Android Google Mobile Ads app ID is not set.
  27. /// - Set minimum API level to 24 (the target API level may be automatically set, we should not
  28. /// hardcode it).
  29. /// - Enable Custom Main Gradle Template.
  30. /// - Update Custom Main Gradle Template with dependencies using the Play Services Resolver.
  31. /// - Enable Custom Gradle Properties Template.
  32. /// - Update Custom Gradle Properties Template with the Jetifier Ignorelist.
  33. /// </summary>
  34. public class AndroidBuildPreProcessor : IPreprocessBuildWithReport
  35. {
  36. private const string NextGenLibrary = "com.google.android.libraries.ads.mobile.sdk:ads-mobile-sdk";
  37. private const string CurrentLibrary = "com.google.android.gms:play-services-ads";
  38. private const string LatestNextGenVersion = "1.6.0";
  39. private const string CurrentVersion = "25.5.0";
  40. private const string NextGenSpec = NextGenLibrary + ":" + LatestNextGenVersion;
  41. private const string CurrentSpec = CurrentLibrary + ":" + CurrentVersion;
  42. private static readonly string NextGenRegex =
  43. Regex.Escape(NextGenLibrary) + @":(?:[\d\.]+[-a-zA-Z0-9]*|LATEST)";
  44. private static readonly string CurrentRegex =
  45. Regex.Escape(CurrentLibrary) + @":(?:[\d\.]+[-a-zA-Z0-9]*|LATEST)";
  46. const int MinimumAPILevel = 24;
  47. const string CustomGradlePropertiesTemplatesFileName = "gradleTemplate.properties";
  48. const string CustomMainGradleTemplateFileName = "mainTemplate.gradle";
  49. const string JetifierEntry =
  50. "android.jetifier.ignorelist=annotation-experimental-1.4.0.aar";
  51. // Set the callback order to be before EDM4U.
  52. // https://github.com/googlesamples/unity-jar-resolver/blob/master/source/AndroidResolver/src/PlayServicesPreBuild.cs#L39
  53. public int callbackOrder { get { return -1; } }
  54. public void OnPreprocessBuild(BuildReport report)
  55. {
  56. UpdateGmaDependency();
  57. if (!GoogleMobileAdsSettings.LoadInstance().EnableGradleBuildPreProcessor)
  58. {
  59. return;
  60. }
  61. // For more details, see https://developers.google.com/admob/unity/android.
  62. #if ANDROID_GRADLE_BUILD_PRE_PROCESSOR_ENABLED
  63. ApplyBuildSettings(report);
  64. #endif
  65. }
  66. private void ApplyBuildSettings(BuildReport report)
  67. {
  68. Debug.Log("Running Android Gradle Build Pre-Processor.");
  69. if (PlayerSettings.Android.minSdkVersion < (AndroidSdkVersions)MinimumAPILevel)
  70. {
  71. PlayerSettings.Android.minSdkVersion = (AndroidSdkVersions)MinimumAPILevel;
  72. Debug.Log($"Set minimum API Level to: {MinimumAPILevel}.");
  73. }
  74. else
  75. {
  76. Debug.Log($"Verified Minimum API Level is >= {MinimumAPILevel}.");
  77. }
  78. // Create Assets/Plugins folder.
  79. if (!AssetDatabase.IsValidFolder(Path.Combine("Assets", "Plugins")))
  80. {
  81. AssetDatabase.CreateFolder("Assets", "Plugins");
  82. AssetDatabase.Refresh();
  83. }
  84. // Create Assets/Plugins/Android folder.
  85. if (!AssetDatabase.IsValidFolder(Path.Combine("Assets", "Plugins", "Android")))
  86. {
  87. AssetDatabase.CreateFolder(Path.Combine("Assets", "Plugins"), "Android");
  88. AssetDatabase.Refresh();
  89. }
  90. // Ensure Custom Main Gradle Template.
  91. EnsureGradleFileExists(CustomMainGradleTemplateFileName);
  92. // Ensure Custom Gradle Properties Templates.
  93. EnsureGradleFileExists(CustomGradlePropertiesTemplatesFileName);
  94. #if ANDROID_GRADLE_BUILD_JETIFIER_ENTRY_ENABLED
  95. string customGradlePropertiesTemplatesFilePath = Path.Combine(
  96. Application.dataPath,
  97. "Plugins", "Android",
  98. CustomGradlePropertiesTemplatesFileName);
  99. if (File.Exists(customGradlePropertiesTemplatesFilePath))
  100. {
  101. var gradlePropertiesFileContent =
  102. File.ReadAllText(customGradlePropertiesTemplatesFilePath);
  103. if (!gradlePropertiesFileContent.Contains(JetifierEntry))
  104. {
  105. File.AppendAllText(
  106. customGradlePropertiesTemplatesFilePath,
  107. Environment.NewLine + JetifierEntry);
  108. Debug.Log("Added Jetifier Entry.");
  109. }
  110. else
  111. {
  112. Debug.Log("Verified Jetifier Entry exists.");
  113. }
  114. }
  115. else
  116. {
  117. Debug.LogError("Failed to add Jetifier Entry.");
  118. }
  119. #endif
  120. Debug.Log("Resolving Android Gradle dependencies.");
  121. ResolvePlayServicesDependencies();
  122. Debug.Log("Android Build Pre-Processor finished.");
  123. }
  124. /// <summary>
  125. /// Runs External Dependency Manager's Android resolution if an EDM is present in the
  126. /// project. EDM is looked up by reflection so that this assembly compiles with Unity's EDM
  127. /// package, Google's legacy EDM, or no EDM at all for publishers who resolve native
  128. /// dependencies with their own tooling.
  129. /// </summary>
  130. private static void ResolvePlayServicesDependencies()
  131. {
  132. Type resolverType = AppDomain.CurrentDomain.GetAssemblies()
  133. .Select(assembly => assembly.GetType("GooglePlayServices.PlayServicesResolver",
  134. false))
  135. .FirstOrDefault(type => type != null);
  136. MethodInfo resolveSync = resolverType?.GetMethod(
  137. "ResolveSync", BindingFlags.Public | BindingFlags.Static, null,
  138. new[] { typeof(bool) }, null);
  139. if (resolveSync == null)
  140. {
  141. const string message =
  142. "External Dependency Manager was not found, so Android " +
  143. "dependency resolution was skipped. Native Android dependencies must be " +
  144. "resolved by your own dependency management tooling.";
  145. if (GoogleMobileAdsSettings.LoadInstance().EnableExternalDependencyManager)
  146. {
  147. Debug.LogWarning(message);
  148. }
  149. else
  150. {
  151. // The publisher opted out of EDM and manages dependencies themselves.
  152. Debug.Log(message);
  153. }
  154. return;
  155. }
  156. try
  157. {
  158. resolveSync.Invoke(null, new object[] { true });
  159. }
  160. catch (TargetInvocationException ex)
  161. {
  162. if (ex.InnerException != null)
  163. {
  164. ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
  165. }
  166. throw;
  167. }
  168. }
  169. /// <summary>
  170. /// Ensures that the given Gradle file exists.
  171. /// </summary>
  172. /// <param name="fileName">name of the given Gradle file.</param>
  173. private void EnsureGradleFileExists(string fileName)
  174. {
  175. bool foundTargetFile = false;
  176. bool foundDisabledFile = false;
  177. // Check for target file.
  178. string targetPath = Path.Combine(Application.dataPath, "Plugins", "Android", fileName);
  179. if (File.Exists(targetPath))
  180. {
  181. foundTargetFile = true;
  182. }
  183. // Check for the ".DISABLED" file.
  184. string disabledPath = Path.Combine(Application.dataPath, "Plugins", "Android",
  185. $"{fileName}.DISABLED");
  186. if (File.Exists(disabledPath))
  187. {
  188. foundDisabledFile = true;
  189. }
  190. // If DISABLED and target exist, delete DISABLED.
  191. if (foundTargetFile && foundDisabledFile)
  192. {
  193. File.Delete(disabledPath);
  194. Debug.Log($"Removed disabled {fileName}.");
  195. return;
  196. }
  197. // If DISABLED exists, move it to target.
  198. if (foundDisabledFile)
  199. {
  200. File.Move(disabledPath, targetPath);
  201. AssetDatabase.Refresh();
  202. Debug.Log($"Enabled {fileName}.");
  203. return;
  204. }
  205. // If target exists, return true.
  206. if (foundTargetFile)
  207. {
  208. Debug.Log($"Verified {fileName}.");
  209. return;
  210. }
  211. // If target does not exist, create it from source.
  212. var unityGradleTemplateDirectory = Path.Combine(
  213. BuildPipeline.GetPlaybackEngineDirectory(BuildTarget.Android, BuildOptions.None),
  214. "Tools",
  215. "GradleTemplates");
  216. string sourceFileName = Path.Combine(unityGradleTemplateDirectory, fileName);
  217. if (!File.Exists(sourceFileName))
  218. {
  219. throw new BuildFailedException(
  220. "Android Build Pre-Processor failed. "+
  221. $"Unable to find source {sourceFileName}. Is your file system read-only?" +
  222. "If this issue persists, contact Google Mobile Ads Support "+
  223. "at https://developers.google.com/admob/support");
  224. }
  225. File.Copy(sourceFileName, targetPath);
  226. AssetDatabase.Refresh();
  227. Debug.Log($"Created {fileName}.");
  228. }
  229. /// <summary>
  230. /// Updates GoogleMobileAdsDependencies.xml with the selected GMA SDK dependency.
  231. /// Existing dependency versions are preserved if the desired GMA SDK is already present.
  232. /// If the file is modified, EDM4U is triggered to resolve dependencies.
  233. /// </summary>
  234. private void UpdateGmaDependency()
  235. {
  236. var pathUtils = ScriptableObject.CreateInstance<EditorPathUtils>();
  237. string directoryPath = pathUtils.GetDirectoryAssetPath();
  238. string dependenciesFilePath =
  239. Path.Combine(directoryPath, "GoogleMobileAdsDependencies.xml");
  240. if (!File.Exists(dependenciesFilePath))
  241. {
  242. Debug.LogError($"GoogleMobileAdsDependencies.xml not found at {dependenciesFilePath}");
  243. return;
  244. }
  245. bool isNextGen = (GoogleMobileAdsSettings.LoadInstance().EffectiveGmaAndroidSdk ==
  246. GoogleMobileAdsSettings.GmaAndroidSdk.NextGen);
  247. string fileContent = File.ReadAllText(dependenciesFilePath);
  248. string desiredRegex = isNextGen ? NextGenRegex : CurrentRegex;
  249. if (Regex.IsMatch(fileContent, desiredRegex))
  250. {
  251. Debug.Log("GoogleMobileAdsDependencies.xml already matches the desired " +
  252. "Google Mobile Ads SDK.");
  253. return;
  254. }
  255. // Identify the regex for the SDK currently in the file to be replaced
  256. // (e.g., if switching to Next Gen, look for the existing Standard SDK to replace).
  257. string targetRegex = isNextGen ? CurrentRegex : NextGenRegex;
  258. if (Regex.IsMatch(fileContent, targetRegex))
  259. {
  260. string desiredSpec = isNextGen ? NextGenSpec : CurrentSpec;
  261. string newContent = Regex.Replace(fileContent, targetRegex, desiredSpec);
  262. Debug.Log($"Updating GoogleMobileAdsDependencies.xml with {desiredSpec}");
  263. File.WriteAllText(dependenciesFilePath, newContent);
  264. AssetDatabase.Refresh();
  265. ResolvePlayServicesDependencies();
  266. }
  267. else
  268. {
  269. Debug.LogWarning(
  270. "Could not find existing Google Mobile Ads SDK dependency in " +
  271. "GoogleMobileAdsDependencies.xml to replace.");
  272. }
  273. }
  274. }
  275. }
  276. #endif