ManifestProcessor.cs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. // Copyright (C) 2020 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #if UNITY_ANDROID
  15. using System.Collections.Generic;
  16. using System.IO;
  17. using System.Linq;
  18. using System.Xml.Linq;
  19. using UnityEditor;
  20. using UnityEditor.Build;
  21. #if UNITY_2018_1_OR_NEWER
  22. using UnityEditor.Build.Reporting;
  23. #endif
  24. using UnityEngine;
  25. namespace GoogleMobileAds.Editor {
  26. #if UNITY_2018_1_OR_NEWER
  27. public class ManifestProcessor : IPreprocessBuildWithReport
  28. #else
  29. public class ManifestProcessor : IPreprocessBuild
  30. #endif
  31. {
  32. private const string MANIFEST_RELATIVE_PATH =
  33. "Plugins/Android/GoogleMobileAdsPlugin.androidlib/AndroidManifest.xml";
  34. private const string PROPERTIES_RELATIVE_PATH =
  35. "Plugins/Android/GoogleMobileAdsPlugin.androidlib/project.properties";
  36. private const string METADATA_APPLICATION_ID = "com.google.android.gms.ads.APPLICATION_ID";
  37. private const string METADATA_DELAY_APP_MEASUREMENT_INIT =
  38. "com.google.android.gms.ads.DELAY_APP_MEASUREMENT_INIT";
  39. private const string METADATA_OPTIMIZE_INITIALIZATION =
  40. "com.google.android.gms.ads.flag.OPTIMIZE_INITIALIZATION";
  41. private const string METADATA_OPTIMIZE_AD_LOADING =
  42. "com.google.android.gms.ads.flag.OPTIMIZE_AD_LOADING";
  43. // LINT.IfChange
  44. private const string METADATA_UNITY_VERSION = "com.google.unity.ads.UNITY_VERSION";
  45. // LINT.ThenChange(//depot/google3/javatests/com/google/android/gmscore/integ/modules/admob/tests/robolectric/src/com/google/android/gms/ads/nonagon/signals/StaticDeviceSignalSourceTest.java)
  46. private XNamespace ns = "http://schemas.android.com/apk/res/android";
  47. public int callbackOrder {
  48. get { return 0; }
  49. }
  50. #if UNITY_2018_1_OR_NEWER
  51. public void OnPreprocessBuild(BuildReport report)
  52. #else
  53. public void OnPreprocessBuild(BuildTarget target, string path)
  54. #endif
  55. {
  56. Debug.Log("Manifest processor triggered during the Player build process.");
  57. string manifestPath = Path.Combine(Application.dataPath, MANIFEST_RELATIVE_PATH);
  58. string propertiesPath = Path.Combine(Application.dataPath, PROPERTIES_RELATIVE_PATH);
  59. /*
  60. * Handle importing GMA via Unity Package Manager.
  61. */
  62. EditorPathUtils pathUtils = ScriptableObject.CreateInstance<EditorPathUtils>();
  63. if (pathUtils.IsPackageRootPath()) {
  64. // pathUtils.GetParentDirectoryAssetPath() returns "Packages/.../GoogleMobileAds" but
  65. // Plugins is at the same level of GoogleMobileAds so we go up one directory before
  66. // appending MANIFEST_RELATIVE_PATH.
  67. string packagesPathPrefix = Path.GetDirectoryName(pathUtils.GetParentDirectoryAssetPath());
  68. manifestPath = Path.Combine(packagesPathPrefix, MANIFEST_RELATIVE_PATH);
  69. propertiesPath = Path.Combine(packagesPathPrefix, PROPERTIES_RELATIVE_PATH);
  70. }
  71. if (AssetDatabase.IsValidFolder("Packages/com.google.ads.mobile")) {
  72. manifestPath = Path.Combine("Packages/com.google.ads.mobile", MANIFEST_RELATIVE_PATH);
  73. }
  74. if (!File.Exists(manifestPath)) {
  75. manifestPath =
  76. Path.Combine(Path.GetDirectoryName(manifestPath), "src", "main", "AndroidManifest.xml");
  77. }
  78. XDocument manifest = null;
  79. try {
  80. manifest = XDocument.Load(manifestPath);
  81. }
  82. #pragma warning disable 0168
  83. catch (IOException e)
  84. #pragma warning restore 0168
  85. {
  86. StopBuildWithMessage("AndroidManifest.xml is missing. Try re-importing the plugin.");
  87. }
  88. XElement elemManifest = manifest.Element("manifest");
  89. if (elemManifest == null) {
  90. StopBuildWithMessage("AndroidManifest.xml is not valid. Try re-importing the plugin.");
  91. }
  92. XElement elemApplication = elemManifest.Element("application");
  93. if (elemApplication == null) {
  94. StopBuildWithMessage("AndroidManifest.xml is not valid. Try re-importing the plugin.");
  95. }
  96. GoogleMobileAdsSettings instance = GoogleMobileAdsSettings.LoadInstance();
  97. string appId = instance.GoogleMobileAdsAndroidAppId.Trim();
  98. if (appId.Length == 0) {
  99. StopBuildWithMessage(
  100. "Android Google Mobile Ads app ID is empty. Please enter a valid app ID to run ads properly.");
  101. }
  102. IEnumerable<XElement> metas =
  103. elemApplication.Descendants().Where(elem => elem.Name.LocalName.Equals("meta-data"));
  104. SetMetadataElement(elemApplication, metas, METADATA_APPLICATION_ID, appId);
  105. SetMetadataElement(elemApplication, metas, METADATA_OPTIMIZE_INITIALIZATION,
  106. !instance.DisableOptimizeInitialization, true);
  107. SetMetadataElement(elemApplication, metas, METADATA_OPTIMIZE_AD_LOADING,
  108. !instance.DisableOptimizeAdLoading, true);
  109. SetMetadataElement(elemApplication, metas, METADATA_UNITY_VERSION, Application.unityVersion);
  110. elemManifest.Save(manifestPath);
  111. }
  112. private XElement CreateMetaElement(string name, object value) {
  113. return new XElement("meta-data", new XAttribute(ns + "name", name),
  114. new XAttribute(ns + "value", value));
  115. }
  116. private XElement GetMetaElement(IEnumerable<XElement> metas, string metaName) {
  117. foreach (XElement elem in metas) {
  118. IEnumerable<XAttribute> attrs = elem.Attributes();
  119. foreach (XAttribute attr in attrs) {
  120. if (attr.Name.Namespace.Equals(ns) && attr.Name.LocalName.Equals("name") &&
  121. attr.Value.Equals(metaName)) {
  122. return elem;
  123. }
  124. }
  125. }
  126. return null;
  127. }
  128. /// <summary>
  129. /// Utility for setting a metadata element
  130. /// </summary>
  131. /// <param name="elemApplication">application element</param>
  132. /// <param name="metas">all metadata elements</param>
  133. /// <param name="metadataName">name of the element to set</param>
  134. /// <param name="metadataValue">value to set</param>
  135. private void SetMetadataElement(XElement elemApplication, IEnumerable<XElement> metas,
  136. string metadataName, string metadataValue) {
  137. XElement element = GetMetaElement(metas, metadataName);
  138. if (element == null) {
  139. elemApplication.Add(CreateMetaElement(metadataName, metadataValue));
  140. } else {
  141. element.SetAttributeValue(ns + "value", metadataValue);
  142. }
  143. }
  144. /// <summary>
  145. /// Utility for setting a metadata element
  146. /// </summary>
  147. /// <param name="elemApplication">application element</param>
  148. /// <param name="metas">all metadata elements</param>
  149. /// <param name="metadataName">name of the element to set</param>
  150. /// <param name="metadataValue">value to set</param>
  151. /// <param name="defaultValue">If metadataValue is default, node will be removed.</param>
  152. private void SetMetadataElement(XElement elemApplication, IEnumerable<XElement> metas,
  153. string metadataName, bool metadataValue,
  154. bool defaultValue = false) {
  155. XElement element = GetMetaElement(metas, metadataName);
  156. if (metadataValue != defaultValue) {
  157. if (element == null) {
  158. elemApplication.Add(CreateMetaElement(metadataName, metadataValue));
  159. } else {
  160. element.SetAttributeValue(ns + "value", metadataValue);
  161. }
  162. } else {
  163. if (element != null) {
  164. element.Remove();
  165. }
  166. }
  167. }
  168. private void StopBuildWithMessage(string message) {
  169. string prefix = "[GoogleMobileAds] ";
  170. #if UNITY_2017_1_OR_NEWER
  171. throw new BuildPlayerWindow.BuildMethodException(prefix + message);
  172. #else
  173. throw new OperationCanceledException(prefix + message);
  174. #endif
  175. }
  176. }
  177. }
  178. #endif