当前位置:   article > 正文

android-gradle-plugin3.0.1源码分析_##{"pluginname":"crashsdk","pluginversionname":"3.

##{"pluginname":"crashsdk","pluginversionname":"3.0.2","pluginversioncod

   学习android的同学都知道android工程从使用android studio开发以后就使用了gradle作为工程的构建工具这就导致我们在了解gradle前提下还要对android-gradle-plugin这个插件有所了解 因为gradle其实就是一个容器或者框架基本上什么工程都可以去构建那如何构建成为android工程呢其实主要的原因就是这个android-gradle-plugin在起作用。代码如下

  1. dependencies {
  2. classpath 'com.android.tools.build:gradle:3.0.1'
  3. }

这段代码大家肯定已经非常的熟悉了这样就相当于我们为gradle框架引入了android-gradle-plugin插件使用这个插件呢也非常的简单只需要在我们工程的build.gradle文件中如下即可

apply plugin: 'com.android.application'

通过Project的apply方法我们就可以使用我们刚刚引入的android-gradle-plugin插件引入了这个插件以后我们就可以使用插件为我们提供的各种属性和方法如下

  1. android {
  2. compileSdkVersion rootProject.ext.compileSdkVersion
  3. buildToolsVersion rootProject.ext.buildToolsVersion
  4. defaultConfig {
  5. applicationId "com.imooc.demo"
  6. minSdkVersion rootProject.ext.minSdkVersion
  7. targetSdkVersion rootProject.ext.targetSdkVersion
  8. versionCode 1
  9. versionName "1.0"
  10. }
  11. buildTypes {
  12. debug {
  13. // 测试混淆
  14. minifyEnabled false
  15. proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
  16. }
  17. }
  18. lintOptions {
  19. checkReleaseBuilds false
  20. abortOnError false
  21. }
  22. compileOptions {
  23. sourceCompatibility rootProject.ext.sourceCompatibility
  24. targetCompatibility rootProject.ext.targetCompatibility
  25. }
  26. configurations.all {
  27. resolutionStrategy.cacheChangingModulesFor 0, 'seconds'
  28. }
  29. }

其实前面这些东西大家学android的一定非常熟悉也不是我们本文章的重点这里我要问大家一个问题为什么我们可以使用android{}这个闭包并且在android{}这个闭包中去配置各种各样的defaultConfig{},buildTypes{}等等这就要说我们本博客的重点android-gradle-plugin.
   既然我们本章的重点是源码分析所以android-gradle-plugin具体如何去使用我们就不再多说下面我们就来看一下android-gradle-plugin的源码是如何工作的。
   首先我们来看一下android-gradle-plugin为我们引入了那些核心类(注意**只列出核心的包和类**)
   第一部分核心类
   
  这个包中的所有类就是我们在配置build.gradle脚本的时候所要用到的下面我们挑最核心的类来为大家讲解一下。其实这个包中看着有这么多类核心中的核心呢其实只有以下三个类大家看我的UML图就可以知道他们的关系

  大家从图中可以看到其实就这三个核心类这三个类的关系呢也可以从UML中看出来另外两个继承于BaseExtension,LibraryExtension和AppExtension其实就是我们上面在build.gradle中写的那个android{}闭包这两个类中只有一个核心方向就是getXXXVariants.是用来获取我们最终的输出变体的我们后面会讲什么是变体(Varitant)。所以这三个核心配置类中基本所有的配置又都在BaseExtension中去定义了下面我们就来看一下这个BaseExtension中的代码

  1. public abstract class BaseExtension implements AndroidConfig {
  2. private final List> transformDependencies = Lists.newArrayList();
  3. private final AndroidBuilder androidBuilder;
  4. private final SdkHandler sdkHandler;
  5. private final DefaultConfig defaultConfig;
  6. private final AaptOptions aaptOptions;
  7. private final LintOptions lintOptions;
  8. private final ExternalNativeBuild externalNativeBuild;
  9. private final DexOptions dexOptions;
  10. private final TestOptions testOptions;
  11. private final CompileOptions compileOptions;
  12. private final PackagingOptions packagingOptions;
  13. private final JacocoOptions jacoco;
  14. private final Splits splits;
  15. private final AdbOptions adbOptions;
  16. private final NamedDomainObjectContainer productFlavors;
  17. private final NamedDomainObjectContainer buildTypes;
  18. private final NamedDomainObjectContainer signingConfigs;
  19. private final NamedDomainObjectContainer buildOutputs;
  20. private final List deviceProviderList = Lists.newArrayList();
  21. private final List testServerList = Lists.newArrayList();
  22. private final List transforms = Lists.newArrayList();
  23. private final DataBindingOptions dataBinding;
  24. private final NamedDomainObjectContainer sourceSetsContainer;
  25. private String target;
  26. private Revision buildToolsRevision;
  27. private List libraryRequests = Lists.newArrayList();
  28. private List flavorDimensionList;
  29. private String resourcePrefix;
  30. private ExtraModelInfo extraModelInfo;
  31. private String defaultPublishConfig = "release";
  32. private Action variantFilter;
  33. protected Logger logger;
  34. private boolean isWritable = true;
  35. protected Project project;
  36. private final ProjectOptions projectOptions;
  37. boolean generatePureSplits = false;
  38. public String getBuildToolsVersion() {
  39. return this.buildToolsRevision.toString();
  40. }
  41. public void setBuildToolsVersion(String version) {
  42. this.buildToolsVersion(version);
  43. }
  44. public void buildTypes(Action<? super NamedDomainObjectContainer> action) {
  45. this.checkWritability();
  46. action.execute(this.buildTypes);
  47. }
  48. public void productFlavors(Action<? super NamedDomainObjectContainer> action) {
  49. this.checkWritability();
  50. action.execute(this.productFlavors);
  51. }
  52. public void signingConfigs(Action<? super NamedDomainObjectContainer> action) {
  53. this.checkWritability();
  54. action.execute(this.signingConfigs);
  55. }
  56. public void flavorDimensions(String... dimensions) {
  57. this.checkWritability();
  58. this.flavorDimensionList = Arrays.asList(dimensions);
  59. }
  60. public void sourceSets(Action> action) {
  61. this.checkWritability();
  62. action.execute(this.sourceSetsContainer);
  63. }
  64. //这个类是个抽象类定义了AppExtension和LibraryExtension中公共的行为实际中使用的还是AppExtension和LibraryExtension.由于这个BaseExtension代码太多我们只取了他的属性和部分方法其他的方法也基本都是对这些属性的操作大家可以自行查看。大家来看这些属性有没有很眼熟的对了像LintOptions,DexOptions,buildTypes,singsConfigs,productFlavors等都可以在这个类中看到所以我们在build.gradle文件中的android{}闭包中可以调用那些方法在我们的这些Extension中都可以找到所以以后想写一个额外的配置直接到这几个XXXExtension中去找对应的方法即可。比如说我们想为不同的flavor的BuildConfig.java类去添加一些属性我们就可以使用BaseFlavor中的buildConfigField()方法去为其添加额外的属性。源码如下
  65. /**
  66. * Adds a new field to the generated BuildConfig class.
  67. *
  68. * <p>The field is generated as: {@code = ;}
  69. *
  70. * </p><p>This means each of these must have valid Java content. If the type is a String, then the
  71. * value should include quotes.
  72. *
  73. * @param type the type of the field
  74. * @param name the name of the field
  75. * @param value the value of the field
  76. */
  77. public void buildConfigField(
  78. @NonNull String type, @NonNull String name, @NonNull String value) {
  79. ClassField alreadyPresent = getBuildConfigFields().get(name);
  80. if (alreadyPresent != null) {
  81. String flavorName = getName();
  82. if (BuilderConstants.MAIN.equals(flavorName)) {
  83. logger.info(
  84. "DefaultConfig: buildConfigField '{}' value is being replaced: {} -> {}",
  85. name,
  86. alreadyPresent.getValue(),
  87. value);
  88. } else {
  89. logger.info(
  90. "ProductFlavor({}): buildConfigField '{}' "
  91. + "value is being replaced: {} -> {}",
  92. flavorName,
  93. name,
  94. alreadyPresent.getValue(),
  95. value);
  96. }
  97. }
  98. addBuildConfigField(new ClassFieldImpl(type, name, value));
  99. }

这个方法大家也应该可以看懂就是开始检查了一下要添加的数据的合法性如果检查通过则将数据包装成一个ClassFieldImpl去添加到一个map中去最终。所以只要熟悉了这几个Extension类那我们就可以去写任意我们需要的配置而不用再担心看不懂别人写的一些build.gradle配置。
   
  好到这里呢我们就可以随心所欲的去编写build.gradle文件了下面我们就开始分析android-gradle-plugin为我们提供的另外一个包中的核心类例如我们刚刚提到的BaseFlavor类其实并不与我们的XXXExtension类在一个包中而是在我们的gradle-core-3.0.1这个jar包中如图:

 

这就是我们今天要重点讲的第二部分比第一部分的内容要多的多这一部分才是我们android-gradle-plugin功能实现在核心老样子我们还是来看下这个包中有那些核心的类这个包中核心的类就比较多了我们来分块看一下。在看代码之前我们要先讲一个概念就是变体Variant,前面我们就提到过的一个概念这个概念是整个android-gradle-plugin最核心的一个概念所有的东西都是在围绕这个Variant去展开的其实一个Variant可以广义的理解为我们生成一个最终的apk过程上中所有的属性方法和Task.也就是说一个Variant定义了我们生成一个Apk所有的东西比如我们可以通过Variant去定义Apk生成的名字路径等等因为我们有Flavor的存在所以一次构建会有多个apk或者aar的输出所以也会有多个Variant的存在。好在理解了这个 Varaint的概念以后我们首先来看源码的第一部分API



第一部分API就有这么多的类不急我们看源码不会看他的所有类只要掌握最核心的那几个类就可以在讲最核心的类之前呢 我们来说一下API这一部分的代码呢就是我们在写build.gradle文件时需要操作Variant时用到所有API部分我们在操作Variant时是不会用到其它类的只会用到这一部分。例如我们在通过Vairant去改变Apk的名字或者生成路径的时候我们用到的API就是ApplicationVariant这个类通过这个类我们就可以去修改到apk的相关东西。这个API包中最核心的类呢其实也只有一个那就是BaseVariant原理与我们前面提到的BaseExtension是一样的在BaseVariant中定义了所有变体最核心最通用的东西下面我们看一下这个BaseVariant这个接口中的源码

  1. /**
  2. * A Build variant and all its public data. This is the base class for items common to apps,
  3. * test apps, and libraries
  4. * 通过上面的这个英文注释大家也可以再次加深对Variant的理解
  5. */
  6. public interface BaseVariant {
  7. /**
  8. * Returns the name of the variant. Guaranteed to be unique.
  9. */
  10. @NonNull
  11. String getName();
  12. /**
  13. * Returns a description for the build variant.
  14. */
  15. @NonNull
  16. String getDescription();
  17. /**
  18. * Returns a subfolder name for the variant. Guaranteed to be unique.
  19. *
  20. * This is usually a mix of build type and flavor(s) (if applicable).
  21. * For instance this could be:
  22. * "debug"
  23. * "debug/myflavor"
  24. * "release/Flavor1Flavor2"
  25. */
  26. @NonNull
  27. String getDirName();
  28. /**
  29. * Returns the base name for the output of the variant. Guaranteed to be unique.
  30. */
  31. @NonNull
  32. String getBaseName();
  33. /**
  34. * Returns the flavor name of the variant. This is a concatenation of all the
  35. * applied flavors
  36. * @return the name of the flavors, or an empty string if there is not flavors.
  37. */
  38. @NonNull
  39. String getFlavorName();
  40. /**
  41. * Returns the variant outputs. There should always be at least one output.
  42. *
  43. * @return a non-null list of variants.
  44. */
  45. @NonNull
  46. DomainObjectCollection getOutputs();
  47. /**
  48. * Returns the {@link com.android.builder.core.DefaultBuildType} for this build variant.
  49. */
  50. @NonNull
  51. BuildType getBuildType();
  52. /**
  53. * Returns a {@link com.android.builder.core.DefaultProductFlavor} that represents the merging
  54. * of the default config and the flavors of this build variant.
  55. */
  56. @NonNull
  57. ProductFlavor getMergedFlavor();
  58. /**
  59. * Returns a {@link JavaCompileOptions} that represents the java compile settings for this build
  60. * variant.
  61. */
  62. @NonNull
  63. JavaCompileOptions getJavaCompileOptions();
  64. /**
  65. * Returns the list of {@link com.android.builder.core.DefaultProductFlavor} for this build
  66. * variant.
  67. *
  68. * </p><p>This is always non-null but could be empty.
  69. */
  70. @NonNull
  71. List getProductFlavors();
  72. /**
  73. * Returns a list of sorted SourceProvider in order of ascending order, meaning, the earlier
  74. * items are meant to be overridden by later items.
  75. *
  76. * @return a list of source provider
  77. */
  78. @NonNull
  79. List getSourceSets();
  80. /**
  81. * Returns a list of FileCollection representing the source folders.
  82. *
  83. * @param folderType the type of folder to return.
  84. * @return a list of folder + dependency as file collections.
  85. */
  86. @NonNull
  87. List getSourceFolders(@NonNull SourceKind folderType);
  88. /** Returns the configuration object for the compilation */
  89. @NonNull
  90. Configuration getCompileConfiguration();
  91. /** Returns the configuration object for the annotation processor. */
  92. @NonNull
  93. Configuration getAnnotationProcessorConfiguration();
  94. /** Returns the configuration object for the runtime */
  95. @NonNull
  96. Configuration getRuntimeConfiguration();
  97. /** Returns the applicationId of the variant. */
  98. @NonNull
  99. String getApplicationId();
  100. /** Returns the pre-build anchor task */
  101. @NonNull
  102. Task getPreBuild();
  103. /**
  104. * Returns the check manifest task.
  105. */
  106. @NonNull
  107. Task getCheckManifest();
  108. /**
  109. * Returns the AIDL compilation task.
  110. */
  111. @NonNull
  112. AidlCompile getAidlCompile();
  113. /**
  114. * Returns the Renderscript compilation task.
  115. */
  116. @NonNull
  117. RenderscriptCompile getRenderscriptCompile();
  118. /**
  119. * Returns the resource merging task.
  120. */
  121. @Nullable
  122. MergeResources getMergeResources();
  123. /**
  124. * Returns the asset merging task.
  125. */
  126. @Nullable
  127. MergeSourceSetFolders getMergeAssets();
  128. /**
  129. * Returns the BuildConfig generation task.
  130. */
  131. @Nullable
  132. GenerateBuildConfig getGenerateBuildConfig();
  133. /**
  134. * Returns the Java Compilation task if javac was configured to compile the source files.
  135. * @deprecated prefer {@link #getJavaCompiler} which always return the java compiler task
  136. * irrespective of which tool chain (javac or jack) used.
  137. */
  138. @Nullable
  139. @Deprecated
  140. JavaCompile getJavaCompile() throws IllegalStateException;
  141. /**
  142. * Returns the Java Compiler task which can be either javac or jack depending on the project
  143. * configuration.
  144. */
  145. @NonNull
  146. Task getJavaCompiler();
  147. /**
  148. * Returns the java compilation classpath.
  149. *
  150. * </p><p>The provided key allows controlling how much of the classpath is returned.
  151. *
  152. * </p><ul><li>
  153. * </li><li>if <code>null</code>, the full classpath is returned
  154. * </li><li>Otherwise the method returns the classpath up to the generated bytecode associated with
  155. * the key
  156. * </li></ul>
  157. *
  158. * @param key the key
  159. * @see #registerGeneratedBytecode(FileCollection)
  160. */
  161. @NonNull
  162. FileCollection getCompileClasspath(@Nullable Object key);
  163. /**
  164. * Returns the java compilation classpath as an ArtifactCollection
  165. *
  166. * <p>The provided key allows controlling how much of the classpath is returned.
  167. *
  168. * </p><ul><li>
  169. * </li><li>if <code>null</code>, the full classpath is returned
  170. * </li><li>Otherwise the method returns the classpath up to the generated bytecode associated with
  171. * the key
  172. * </li></ul>
  173. *
  174. * @param key the key
  175. * @see #registerGeneratedBytecode(FileCollection)
  176. */
  177. @NonNull
  178. ArtifactCollection getCompileClasspathArtifacts(@Nullable Object key);
  179. /**
  180. * Returns the file and task dependency of the folder containing all the merged data-binding
  181. * artifacts coming from the dependency.
  182. *
  183. * <p>If data-binding is not enabled the file collection will be empty.
  184. *
  185. * @return the file collection containing the folder or nothing.
  186. */
  187. @NonNull
  188. FileCollection getDataBindingDependencyArtifacts();
  189. /** Returns the NDK Compilation task. */
  190. @NonNull
  191. NdkCompile getNdkCompile();
  192. /**
  193. * Returns the tasks for building external native projects.
  194. */
  195. Collection getExternalNativeBuildTasks();
  196. /**
  197. * Returns the obfuscation task. This can be null if obfuscation is not enabled.
  198. */
  199. @Nullable
  200. Task getObfuscation();
  201. /**
  202. * Returns the obfuscation mapping file. This can be null if obfuscation is not enabled.
  203. */
  204. @Nullable
  205. File getMappingFile();
  206. /**
  207. * Returns the Java resource processing task.
  208. */
  209. @NonNull
  210. AbstractCopyTask getProcessJavaResources();
  211. /**
  212. * Returns the assemble task for all this variant's output
  213. */
  214. @Nullable
  215. Task getAssemble();
  216. /**
  217. * Adds new Java source folders to the model.
  218. *
  219. * These source folders will not be used for the default build
  220. * system, but will be passed along the default Java source folders
  221. * to whoever queries the model.
  222. *
  223. * @param sourceFolders the source folders where the generated source code is.
  224. */
  225. void addJavaSourceFoldersToModel(@NonNull File... sourceFolders);
  226. /**
  227. * Adds new Java source folders to the model.
  228. *
  229. * These source folders will not be used for the default build
  230. * system, but will be passed along the default Java source folders
  231. * to whoever queries the model.
  232. *
  233. * @param sourceFolders the source folders where the generated source code is.
  234. */
  235. void addJavaSourceFoldersToModel(@NonNull Collection sourceFolders);
  236. /**
  237. * Adds to the variant a task that generates Java source code.
  238. *
  239. * This will make the generate[Variant]Sources task depend on this task and add the
  240. * new source folders as compilation inputs.
  241. *
  242. * The new source folders are also added to the model.
  243. *
  244. * @param task the task
  245. * @param sourceFolders the source folders where the generated source code is.
  246. */
  247. void registerJavaGeneratingTask(@NonNull Task task, @NonNull File... sourceFolders);
  248. /**
  249. * Adds to the variant a task that generates Java source code.
  250. *
  251. * This will make the generate[Variant]Sources task depend on this task and add the
  252. * new source folders as compilation inputs.
  253. *
  254. * The new source folders are also added to the model.
  255. *
  256. * @param task the task
  257. * @param sourceFolders the source folders where the generated source code is.
  258. */
  259. void registerJavaGeneratingTask(@NonNull Task task, @NonNull Collection sourceFolders);
  260. /**
  261. * Register the output of an external annotation processor.
  262. *
  263. * </p><p>The output is passed to the javac task, but the source generation hooks does not depend on
  264. * this.
  265. *
  266. * </p><p>In order to properly wire up tasks, the FileTree object must include dependency
  267. * information about the task that generates the content of this folders.
  268. *
  269. * @param folder a ConfigurableFileTree that contains a single folder and the task dependency
  270. * information
  271. */
  272. void registerExternalAptJavaOutput(@NonNull ConfigurableFileTree folder);
  273. /**
  274. * Adds to the variant new generated resource folders.
  275. *
  276. * </p><p>In order to properly wire up tasks, the FileCollection object must include dependency
  277. * information about the task that generates the content of this folders.
  278. *
  279. * @param folders a FileCollection that contains the folders and the task dependency information
  280. */
  281. void registerGeneratedResFolders(@NonNull FileCollection folders);
  282. /**
  283. * Adds to the variant a task that generates Resources.
  284. *
  285. * This will make the generate[Variant]Resources task depend on this task and add the
  286. * new Resource folders as Resource merge inputs.
  287. *
  288. * The Resource folders are also added to the model.
  289. *
  290. * @param task the task
  291. * @param resFolders the folders where the generated resources are.
  292. *
  293. * @deprecated Use {@link #registerGeneratedResFolders(FileCollection)}
  294. */
  295. @Deprecated
  296. void registerResGeneratingTask(@NonNull Task task, @NonNull File... resFolders);
  297. /**
  298. * Adds to the variant a task that generates Resources.
  299. *
  300. * This will make the generate[Variant]Resources task depend on this task and add the
  301. * new Resource folders as Resource merge inputs.
  302. *
  303. * The Resource folders are also added to the model.
  304. *
  305. * @param task the task
  306. * @param resFolders the folders where the generated resources are.
  307. *
  308. * @deprecated Use {@link #registerGeneratedResFolders(FileCollection)}
  309. */
  310. @Deprecated
  311. void registerResGeneratingTask(@NonNull Task task, @NonNull Collection resFolders);
  312. /**
  313. * Adds to the variant new generated Java byte-code.
  314. *
  315. * </p><p>This bytecode is passed to the javac classpath. This is typically used by compilers for
  316. * languages that generate bytecode ahead of javac.
  317. *
  318. * </p><p>The file collection can contain either a folder of class files or jars.
  319. *
  320. * </p><p>In order to properly wire up tasks, the FileCollection object must include dependency
  321. * information about the task that generates the content of these folders. This is generally
  322. * setup using {@link org.gradle.api.file.ConfigurableFileCollection#builtBy(Object...)}
  323. *
  324. * </p><p>The generated byte-code will also be added to the transform pipeline as a {@link
  325. * com.android.build.api.transform.QualifiedContent.Scope#PROJECT} stream.
  326. *
  327. * </p><p>The method returns a key that can be used to query for the compilation classpath. This
  328. * allows each successive call to {@link #registerPreJavacGeneratedBytecode(FileCollection)} to
  329. * be associated with a classpath containing everything <strong>before</strong> the added
  330. * bytecode.
  331. *
  332. * @param fileCollection a FileCollection that contains the files and the task dependency
  333. * information
  334. * @return a key for calls to {@link #registerGeneratedBytecode(FileCollection)}
  335. */
  336. Object registerPreJavacGeneratedBytecode(@NonNull FileCollection fileCollection);
  337. /** @deprecated use {@link #registerPreJavacGeneratedBytecode(FileCollection)} */
  338. @Deprecated
  339. Object registerGeneratedBytecode(@NonNull FileCollection fileCollection);
  340. /**
  341. * Adds to the variant new generated Java byte-code.
  342. *
  343. * </p><p>This bytecode is meant to be post javac, which means javac does not have it on its
  344. * classpath. It's is only added to the java compilation task's classpath and will be added to
  345. * the transform pipeline as a {@link
  346. * com.android.build.api.transform.QualifiedContent.Scope#PROJECT} stream.
  347. *
  348. * </p><p>The file collection can contain either a folder of class files or jars.
  349. *
  350. * </p><p>In order to properly wire up tasks, the FileCollection object must include dependency
  351. * information about the task that generates the content of these folders. This is generally
  352. * setup using {@link org.gradle.api.file.ConfigurableFileCollection#builtBy(Object...)}
  353. *
  354. * @param fileCollection a FileCollection that contains the files and the task dependency
  355. * information
  356. */
  357. void registerPostJavacGeneratedBytecode(@NonNull FileCollection fileCollection);
  358. /**
  359. * Adds a variant-specific BuildConfig field.
  360. *
  361. * @param type the type of the field
  362. * @param name the name of the field
  363. * @param value the value of the field
  364. */
  365. void buildConfigField(@NonNull String type, @NonNull String name, @NonNull String value);
  366. /**
  367. * Adds a variant-specific res value.
  368. * @param type the type of the field
  369. * @param name the name of the field
  370. * @param value the value of the field
  371. */
  372. void resValue(@NonNull String type, @NonNull String name, @NonNull String value);
  373. /**
  374. * Set up a new matching request for a given flavor dimension and value.
  375. *
  376. * </p><p>To learn more, read <a href="d.android.com/r/tools/use-flavorSelection.html">Select
  377. * default flavors for missing dimensions</a>.
  378. *
  379. * @param dimension the flavor dimension
  380. * @param requestedValue the flavor name
  381. */
  382. void missingDimensionStrategy(@NonNull String dimension, @NonNull String requestedValue);
  383. /**
  384. * Set up a new matching request for a given flavor dimension and value.
  385. *
  386. * </p><p>To learn more, read <a href="d.android.com/r/tools/use-flavorSelection.html">Select
  387. * default flavors for missing dimensions</a>.
  388. *
  389. * @param dimension the flavor dimension
  390. * @param requestedValues the flavor name and fallbacks
  391. */
  392. void missingDimensionStrategy(@NonNull String dimension, @NonNull String... requestedValues);
  393. /**
  394. * Set up a new matching request for a given flavor dimension and value.
  395. *
  396. * </p><p>To learn more, read <a href="d.android.com/r/tools/use-flavorSelection.html">Select
  397. * default flavors for missing dimensions</a>.
  398. *
  399. * @param dimension the flavor dimension
  400. * @param requestedValues the flavor name and fallbacks
  401. */
  402. void missingDimensionStrategy(@NonNull String dimension, @NonNull List requestedValues);
  403. /**
  404. * If true, variant outputs will be considered signed. Only set if you manually set the outputs
  405. * to point to signed files built by other tasks.
  406. */
  407. void setOutputsAreSigned(boolean isSigned);
  408. /**
  409. * @see #setOutputsAreSigned(boolean)
  410. */
  411. boolean getOutputsAreSigned();
  412. }

从头看下来以后通过这个类我们几乎可以得到关于Variant的所有信息例如Variant的name,  description, buildtype等当然还可以得到在生成最终Apk过程中的相关Task, Task我们放在最后去看因为是最复杂的一部分。既然第一部分都是些API部分让我们直接程序员去直接调用那这些接口的实际实现都在那里呢我们看源码当然不能只看这些空的API了那么上面的这些API的具体实现就是我们要去看的第二部分如图

所有API的实现呢都在**internal/api**这个包中大家从类的名字也可以看出来后面基本都带有impl表示实现的意思那既然我们的接口中核心是BaseVariant这个接口所以我们可以确定他的实现中BaseVarintImpl当然也是实现中的核心所以我们就来看下BaseVarintImpl这个实现类的源码
  1. public abstract class BaseVariantImpl implements BaseVariant {
  2. @NonNull private final ObjectFactory objectFactory;
  3. @NonNull protected final AndroidBuilder androidBuilder;
  4. @NonNull protected final ReadOnlyObjectProvider readOnlyObjectProvider;
  5. @NonNull protected final NamedDomainObjectContainer outputs;
  6. BaseVariantImpl(
  7. @NonNull ObjectFactory objectFactory,
  8. @NonNull AndroidBuilder androidBuilder,
  9. @NonNull ReadOnlyObjectProvider readOnlyObjectProvider,
  10. @NonNull NamedDomainObjectContainer outputs) {
  11. this.objectFactory = objectFactory;
  12. this.androidBuilder = androidBuilder;
  13. this.readOnlyObjectProvider = readOnlyObjectProvider;
  14. this.outputs = outputs;
  15. }
  16. @NonNull
  17. protected abstract BaseVariantData getVariantData();
  18. public void addOutputs(@NonNull List outputs) {
  19. this.outputs.addAll(outputs);
  20. }
  21. @Override
  22. @NonNull
  23. public String getName() {
  24. return getVariantData().getVariantConfiguration().getFullName();
  25. }
  26. @Override
  27. @NonNull
  28. public String getDescription() {
  29. return getVariantData().getDescription();
  30. }
  31. @Override
  32. @NonNull
  33. public String getDirName() {
  34. return getVariantData().getVariantConfiguration().getDirName();
  35. }
  36. @Override
  37. @NonNull
  38. public String getBaseName() {
  39. return getVariantData().getVariantConfiguration().getBaseName();
  40. }
  41. @NonNull
  42. @Override
  43. public String getFlavorName() {
  44. return getVariantData().getVariantConfiguration().getFlavorName();
  45. }
  46. @NonNull
  47. @Override
  48. public DomainObjectCollection getOutputs() {
  49. return outputs;
  50. }
  51. @Override
  52. @NonNull
  53. public BuildType getBuildType() {
  54. return readOnlyObjectProvider.getBuildType(
  55. getVariantData().getVariantConfiguration().getBuildType());
  56. }
  57. @Override
  58. @NonNull
  59. public List getProductFlavors() {
  60. return new ImmutableFlavorList(
  61. getVariantData().getVariantConfiguration().getProductFlavors(),
  62. readOnlyObjectProvider);
  63. }
  64. @Override
  65. @NonNull
  66. public ProductFlavor getMergedFlavor() {
  67. return getVariantData().getVariantConfiguration().getMergedFlavor();
  68. }
  69. }
  70. ```
  71. 这里我没有完全copy出源码来为了不让我们的版面看起来太多从我copy出来的这几个方法大家可以看到他确实继成了我们的BaseVariant这个接口然后对这些方法都进行了实现看他的实现的时候我们可以发现几乎都是调用了getVariantData()这个方法里的实现所以我们可以再往下看源码的时候就要看BaseVariantData这个类究尽是如何实现这些方法的我们拿一个比较常用的buildConfigField这个方法来看一下源码如下
  72. ```
  73. @Override
  74. public void buildConfigField(
  75. @NonNull String type, @NonNull String name, @NonNull String value) {
  76. getVariantData().getVariantConfiguration().addBuildConfigField(type, name, value);
  77. }
  78. ```
  79. 可以看到BaseVariantImpl中对于buildConfigField的实现就是调用BaseVariantData中的configuration实现的我们来看一下最终他是如何去实现的代码如下
  80. ```
  81. private final Map mBuildConfigFields;
  82. public void addBuildConfigField(String type, String name, String value) {
  83. ClassField classField = new ClassFieldImpl(type, name, value);
  84. this.mBuildConfigFields.put(name, classField);
  85. }
  86. ```
  87. 可以看到最后的实现就是将我们的数据包装成ClassField放到了一个map中没有任何复杂的地方。
  88. 我们现来分析一个在BaseVariantImpl中有一个方法如下
  89. ```
  90. @Override
  91. public void registerJavaGeneratingTask(@NonNull Task task, @NonNull Collection sourceFolders) {
  92. getVariantData().registerJavaGeneratingTask(task, sourceFolders);
  93. }
  94. ```
  95. 这个方法的作用是我们可以通过此方法定义一个Task去生成一个java文件同时可以让生成的java文件被编译成class字节码他的实现同样是通过BaseVariantData实现的我们来看一下具体的实现
  96. ```
  97. public void registerJavaGeneratingTask(@NonNull Task task, @NonNull Collection generatedSourceFolders) {
  98. Preconditions.checkNotNull(javacTask);
  99. //将插件原来的源码生成Task依赖于我们的Task,保证我们Task也能被执行到
  100. sourceGenTask.dependsOn(task);
  101. final Project project = scope.getGlobalScope().getProject();
  102. if (extraGeneratedSourceFileTrees == null) {
  103. extraGeneratedSourceFileTrees = new ArrayList<>();
  104. }
  105. for (File f : generatedSourceFolders) {
  106. ConfigurableFileTree fileTree = project.fileTree(f).builtBy(task);
  107. //将外部生成的java文件添到加源码树中
  108. extraGeneratedSourceFileTrees.add(fileTree);
  109. //将我们生成的java文件树添加到javaC Task中这样我们额外生成的类也可以被编译成class字节码
  110. javacTask.source(fileTree);
  111. }
  112. addJavaSourceFoldersToModel(generatedSourceFolders);
  113. }
  114. ```
  115. 好通过我在源码中添加的注释相信大家可以知道这个方法为什么可以动态的去添加java文件的生成和编译了。所以如果大家对其它方法的实现感兴趣可以重点去看这两个类中的实现即可所以在我们第二部分中最重要的两个类就是BaseVaraintImpl和BaseVariantData其它的类都是一些辅助类。
  116. 第三个比较重要的部分就是一些其它类的实现下面我们来看一下这些类所在的一个位置
  117. ![图片描述][7]
  1. 在这个dsl包中的类呢就是一些辅助BaseVariant中的一些类比如我们的BuildType构建类型BaseFlavor渠道类等等这些类大家应该看起来比较容易理解所以如果大家想看在buildType{}中可以调用那些方法就直接去看BuildType类中有那些方法即可下面我们来看一个我们最常用的DefalueConfig类这个类就对应于我们在build.gradle文件中写defaultConfig{},我们来看一下他的源码
  2. ```
  3. /** DSL object for the defaultConfig object. */
  4. @SuppressWarnings({"WeakerAccess", "unused"}) // Exposed in the DSL.
  5. public class DefaultConfig extends BaseFlavor {
  6. public DefaultConfig(
  7. @NonNull String name,
  8. @NonNull Project project,
  9. @NonNull Instantiator instantiator,
  10. @NonNull Logger logger,
  11. @NonNull ErrorReporter errorReporter) {
  12. super(name, project, instantiator, logger, errorReporter);
  13. }
  14. }

  1. public abstract class BaseVariantImpl implements BaseVariant {
  2. @NonNull private final ObjectFactory objectFactory;
  3. @NonNull protected final AndroidBuilder androidBuilder;
  4. @NonNull protected final ReadOnlyObjectProvider readOnlyObjectProvider;
  5. @NonNull protected final NamedDomainObjectContainer outputs;
  6. BaseVariantImpl(
  7. @NonNull ObjectFactory objectFactory,
  8. @NonNull AndroidBuilder androidBuilder,
  9. @NonNull ReadOnlyObjectProvider readOnlyObjectProvider,
  10. @NonNull NamedDomainObjectContainer outputs) {
  11. this.objectFactory = objectFactory;
  12. this.androidBuilder = androidBuilder;
  13. this.readOnlyObjectProvider = readOnlyObjectProvider;
  14. this.outputs = outputs;
  15. }
  16. @NonNull
  17. protected abstract BaseVariantData getVariantData();
  18. public void addOutputs(@NonNull List outputs) {
  19. this.outputs.addAll(outputs);
  20. }
  21. @Override
  22. @NonNull
  23. public String getName() {
  24. return getVariantData().getVariantConfiguration().getFullName();
  25. }
  26. @Override
  27. @NonNull
  28. public String getDescription() {
  29. return getVariantData().getDescription();
  30. }
  31. @Override
  32. @NonNull
  33. public String getDirName() {
  34. return getVariantData().getVariantConfiguration().getDirName();
  35. }
  36. @Override
  37. @NonNull
  38. public String getBaseName() {
  39. return getVariantData().getVariantConfiguration().getBaseName();
  40. }
  41. @NonNull
  42. @Override
  43. public String getFlavorName() {
  44. return getVariantData().getVariantConfiguration().getFlavorName();
  45. }
  46. @NonNull
  47. @Override
  48. public DomainObjectCollection getOutputs() {
  49. return outputs;
  50. }
  51. @Override
  52. @NonNull
  53. public BuildType getBuildType() {
  54. return readOnlyObjectProvider.getBuildType(
  55. getVariantData().getVariantConfiguration().getBuildType());
  56. }
  57. @Override
  58. @NonNull
  59. public List getProductFlavors() {
  60. return new ImmutableFlavorList(
  61. getVariantData().getVariantConfiguration().getProductFlavors(),
  62. readOnlyObjectProvider);
  63. }
  64. @Override
  65. @NonNull
  66. public ProductFlavor getMergedFlavor() {
  67. return getVariantData().getVariantConfiguration().getMergedFlavor();
  68. }
  69. }
  70. ```
  71. 这里我没有完全copy出源码来为了不让我们的版面看起来太多从我copy出来的这几个方法大家可以看到他确实继成了我们的BaseVariant这个接口然后对这些方法都进行了实现看他的实现的时候我们可以发现几乎都是调用了getVariantData()这个方法里的实现所以我们可以再往下看源码的时候就要看BaseVariantData这个类究尽是如何实现这些方法的我们拿一个比较常用的buildConfigField这个方法来看一下源码如下
  72. ```
  73. @Override
  74. public void buildConfigField(
  75. @NonNull String type, @NonNull String name, @NonNull String value) {
  76. getVariantData().getVariantConfiguration().addBuildConfigField(type, name, value);
  77. }
  78. ```
  79. 可以看到BaseVariantImpl中对于buildConfigField的实现就是调用BaseVariantData中的configuration实现的我们来看一下最终他是如何去实现的代码如下
  80. ```
  81. private final Map mBuildConfigFields;
  82. public void addBuildConfigField(String type, String name, String value) {
  83. ClassField classField = new ClassFieldImpl(type, name, value);
  84. this.mBuildConfigFields.put(name, classField);
  85. }
  86. ```
  87. 可以看到最后的实现就是将我们的数据包装成ClassField放到了一个map中没有任何复杂的地方。
  88. 我们现来分析一个在BaseVariantImpl中有一个方法如下
  89. ```
  90. @Override
  91. public void registerJavaGeneratingTask(@NonNull Task task, @NonNull Collection sourceFolders) {
  92. getVariantData().registerJavaGeneratingTask(task, sourceFolders);
  93. }
  94. ```
  95. 这个方法的作用是我们可以通过此方法定义一个Task去生成一个java文件同时可以让生成的java文件被编译成class字节码他的实现同样是通过BaseVariantData实现的我们来看一下具体的实现
  96. ```
  97. public void registerJavaGeneratingTask(@NonNull Task task, @NonNull Collection generatedSourceFolders) {
  98. Preconditions.checkNotNull(javacTask);
  99. //将插件原来的源码生成Task依赖于我们的Task,保证我们Task也能被执行到
  100. sourceGenTask.dependsOn(task);
  101. final Project project = scope.getGlobalScope().getProject();
  102. if (extraGeneratedSourceFileTrees == null) {
  103. extraGeneratedSourceFileTrees = new ArrayList<>();
  104. }
  105. for (File f : generatedSourceFolders) {
  106. ConfigurableFileTree fileTree = project.fileTree(f).builtBy(task);
  107. //将外部生成的java文件添到加源码树中
  108. extraGeneratedSourceFileTrees.add(fileTree);
  109. //将我们生成的java文件树添加到javaC Task中这样我们额外生成的类也可以被编译成class字节码
  110. javacTask.source(fileTree);
  111. }
  112. addJavaSourceFoldersToModel(generatedSourceFolders);
  113. }
  114. ```
  115. 好通过我在源码中添加的注释相信大家可以知道这个方法为什么可以动态的去添加java文件的生成和编译了。所以如果大家对其它方法的实现感兴趣可以重点去看这两个类中的实现即可所以在我们第二部分中最重要的两个类就是BaseVaraintImpl和BaseVariantData其它的类都是一些辅助类。
  116. 第三个比较重要的部分就是一些其它类的实现下面我们来看一下这些类所在的一个位置
  117. ![图片描述][7]
  118. 在这个dsl包中的类呢就是一些辅助BaseVariant中的一些类比如我们的BuildType构建类型BaseFlavor渠道类等等这些类大家应该看起来比较容易理解所以如果大家想看在buildType{}中可以调用那些方法就直接去看BuildType类中有那些方法即可下面我们来看一个我们最常用的DefalueConfig类这个类就对应于我们在build.gradle文件中写defaultConfig{},我们来看一下他的源码
  119. ```
  120. /** DSL object for the defaultConfig object. */
  121. @SuppressWarnings({"WeakerAccess", "unused"}) // Exposed in the DSL.
  122. public class DefaultConfig extends BaseFlavor {
  123. public DefaultConfig(
  124. @NonNull String name,
  125. @NonNull Project project,
  126. @NonNull Instantiator instantiator,
  127. @NonNull Logger logger,
  128. @NonNull ErrorReporter errorReporter) {
  129. super(name, project, instantiator, logger, errorReporter);
  130. }
  131. }

可见这个类是继成于我们前面提到过的BaseFlavor类我们再来看一下BaseFlavor中的源码
  1. public void minSdkVersion(int minSdkVersion) {
  2. setMinSdkVersion(minSdkVersion);
  3. }
  4. public void setMinSdkVersion(@Nullable String minSdkVersion) {
  5. setMinSdkVersion(getApiVersion(minSdkVersion));
  6. }
  7. /**
  8. * Sets minimum SDK version.
  9. *
  10. * </p><p>See <a href="http://developer.android.com/guide/topics/manifest/uses-sdk-element.html">
  11. * uses-sdk element documentation</a>.
  12. */
  13. public void minSdkVersion(@Nullable String minSdkVersion) {
  14. setMinSdkVersion(minSdkVersion);
  15. }
  16. @NonNull
  17. public com.android.builder.model.ProductFlavor setTargetSdkVersion(int targetSdkVersion) {
  18. setTargetSdkVersion(new DefaultApiVersion(targetSdkVersion));
  19. return this;
  20. }
  21. /**
  22. * Sets the target SDK version to the given value.
  23. *
  24. * </p><p>See <a href="http://developer.android.com/guide/topics/manifest/uses-sdk-element.html">
  25. * uses-sdk element documentation</a>.
  26. */
  27. public void targetSdkVersion(int targetSdkVersion) {
  28. setTargetSdkVersion(targetSdkVersion);
  29. }
  30. public void setTargetSdkVersion(@Nullable String targetSdkVersion) {
  31. setTargetSdkVersion(getApiVersion(targetSdkVersion));
  32. }
  33. /**
  34. * Sets the target SDK version to the given value.
  35. *
  36. * </p><p>See <a href="http://developer.android.com/guide/topics/manifest/uses-sdk-element.html">
  37. * uses-sdk element documentation</a>.
  38. */
  39. public void targetSdkVersion(@Nullable String targetSdkVersion) {
  40. setTargetSdkVersion(targetSdkVersion);
  41. }
大家可以看到我们最常见的minSdkVersion, targetSdkVersion等常用方法。所以这个包中的类也是比较重要的大家有时间的话也可以整体过一下熟悉他们的实现当然无需每行代码都看懂知道他的一些核心方法和作用即可。


源码中的最后一部分是我们整个androd-gradle-plugin最核心也是最复杂的一部分也就是Task部分我们先来看一下Task这部分的源码位置如图

 为什么说这最后一部分Task是最重要的呢学习过gradle的人都应该知道Task才是真正的执行逻辑也就是说我们前面通过XXXExtension等进行的各种配置还只是一些配置没有其它任何作用只有结合了我们的Task,才能真正的将前面所有的配置都写到我们最终生成的APK中的对应文件中去也就是前面的各种配置是我们的构思是Task让我们的构思得到了实现举个栗子我们在写build.gradle文件时通过productflavor编写了什么百度google,xiaomi等渠道如果没有对应的Task去处理这些渠道那你怎么写都没有用。这个包中的Task这么多一个个去看他们的源码显然不太可能下面给大家推荐一篇文章以里有一些重要的Task的一些作用[Gradle Android插件用户指南][9]下面我来为大家阅读一个常见的Task的执行前面我们讲解了如何使用buildConfigFiled来为不同的flavor去添加一些属性下面我们来看看通过这个方法添加的属性最后是如何被写入到java源文件中去的。源码如下
  1. @CacheableTask public class GenerateBuildConfig extends BaseTask {
  2. //所有要写入到java源文件的属性存在一个list中
  3. private Supplier> items;
  4. //Task的真正执行逻辑
  5. @TaskAction void generate() throws IOException {
  6. // must clear the folder in case the packagename changed, otherwise,
  7. // there'll be two classes.
  8. File destinationDir = getSourceOutputDir();
  9. FileUtils.cleanOutputDir(destinationDir);
  10. //BuildConfig.java源文件的一个生成辅助类
  11. BuildConfigGenerator generator =
  12. new BuildConfigGenerator(getSourceOutputDir(), getBuildConfigPackageName());
  13. //添加一些取基础属性从这里我们可以知道为什么BuildConfig.java这个类中总是有这些属性的存在
  14. generator.addField("boolean", "DEBUG",
  15. isDebuggable() ? "Boolean.parseBoolean(\"true\")" : "false")
  16. .addField("String", "APPLICATION_ID", '"' + appPackageName.get() + '"')
  17. .addField("String", "BUILD_TYPE", '"' + getBuildTypeName() + '"')
  18. .addField("String", "FLAVOR", '"' + getFlavorName() + '"')
  19. .addField("int", "VERSION_CODE", Integer.toString(getVersionCode()))
  20. .addField("String", "VERSION_NAME", '"' + Strings.nullToEmpty(getVersionName()) + '"')
  21. //将我们在外部动态添加的属性一同写入
  22. .addItems(getItems());
  23. List flavors = getFlavorNamesWithDimensionNames();
  24. int count = flavors.size();
  25. if (count > 1) {
  26. for (int i = 0; i < count; i += 2) {
  27. generator.addField("String", "FLAVOR_" + flavors.get(i + 1), '"' + flavors.get(i) + '"');
  28. }
  29. }
  30. //通过辅助类生成java文件
  31. generator.generate();
  32. }
  33. //这里我把BuildConfigFiledGenerator的核心generate()方法取出大家可以看到这个方法无非就是一个文件的写没有其它复杂的
  34. public void generate() throws IOException {
  35. File pkgFolder = this.getFolderPath();
  36. if(!pkgFolder.isDirectory() && !pkgFolder.mkdirs()) {
  37. throw new RuntimeException("Failed to create " + pkgFolder.getAbsolutePath());
  38. } else {
  39. File buildConfigJava = new File(pkgFolder, "BuildConfig.java");
  40. Closer closer = Closer.create();
  41. try {
  42. FileOutputStream fos = (FileOutputStream)closer.register(new FileOutputStream(buildConfigJava));
  43. OutputStreamWriter out = (OutputStreamWriter)closer.register(new OutputStreamWriter(fos, Charsets.UTF_8));
  44. JavaWriter writer = (JavaWriter)closer.register(new JavaWriter(out));
  45. writer.emitJavadoc("Automatically generated file. DO NOT MODIFY", new Object[0]).emitPackage(this.mBuildConfigPackageName).beginType("BuildConfig", "class", PUBLIC_FINAL);
  46. Iterator var7 = this.mFields.iterator();
  47. while(var7.hasNext()) {
  48. ClassField field = (ClassField)var7.next();
  49. emitClassField(writer, field);
  50. }
  51. var7 = this.mItems.iterator();
  52. while(var7.hasNext()) {
  53. Object item = var7.next();
  54. if(item instanceof ClassField) {
  55. emitClassField(writer, (ClassField)item);
  56. } else if(item instanceof String) {
  57. writer.emitSingleLineComment((String)item, new Object[0]);
  58. }
  59. }
  60. writer.endType();
  61. } catch (Throwable var12) {
  62. throw closer.rethrow(var12);
  63. } finally {
  64. closer.close();
  65. }
  66. }
  67. }
  68. }

  其它的Task分析流程基本一样大家只要关注他的核心变量和被@TaskAction注解的方法即可。从这个Task我们可以看出无论你前面怎么配置如果没有Task 最后将那个List写入到java源文件中去都是白费所以Task才是真正最核心的地方。其它一些比较重要的Task如ProcessManifest,GenerateResValues等大家也可以过一下他们的核心逻辑。讲到现在我们可以看到android-gradle-plugin两个核心包中的类虽然挺多但是通过我们进行分析以后我们开发人员重点关注它的一些核心类即可。总后总结一下Variant的概念大家一定要理解最后问大家一个问题这两个核心jar包是如何关联起来的呢就是通过Variant.大家通过下面我的这张UML图就可以看出来如图:



通过这张图大家也可以看到两个不同的包的一些核心类的继承关系。好的对android-gradle-plugin的源码分析就到这里大家有什么疑问可以在下方议论留言。欢迎点赞</p>

欢迎关注课程:  《Gradle3.0自动化项目构建技术精讲》

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/285479
推荐阅读
相关标签
  

闽ICP备14008679号