首先我要说明一下,本篇文章是基于3.0.0版本的Gradle 插件源码进行分析的。
1 源码下载
既然要进行源码分析,首先就是要下载源码,这个官方给出了详细的步骤:
gradle插件源码的下载和编译
上面的文章下载了Android Studio 和Gradle插件所有版本的源码,而我只是研究3.0.0版本的Gradle 插件源码,所以就手动在下载了3.0.0版本的Gradle 插件源码。
然后用Android Studio打开大概如下图所示:
上图中框住的3个目录就是Gradle插件相关的源码。
2 com.android.application插件apply流程源码解析
当我们新建一个Android项目Demo时,Demo项目结构如下图:
上图中框住的部分就是用来导入用于构建Android项目的Gradle 插件库,具体请参考Gradle系列一 -- Groovy、Gradle和自定义Gradle插件, 那该Gradle 插件库包含了多少插件呢:
上图红框中就是3.0.0版本的Gradle 插件库中包含的所有插件,一共有10个,其中有一个名称为com.android.application的properties文件,文件的名称是apply该文件中描述的插件(即com.android.build.gradle.AppPlugin)的标识,下面再来看一看Demo项目中app module的build.gradle文件:
上图红框中的内容就是执行com.android.application插件(即执行com.android.build.gradle.AppPlugin的apply方法)的apply方法的,那接下来就看看apply方法的执行流程,首先通过下面的时序图概括下:
首先看一下第一步com.android.build.gradle.AppPlugin的apply方法源码:
@Override
public void apply(@NonNull Project project) {
super.apply(project);
}
可以看到,直接调用父类BasePlugin的apply方法(即第二步):
protected void apply(@NonNull Project project) {
......
threadRecorder.record(
ExecutionType.BASE_PLUGIN_PROJECT_BASE_EXTENSION_CREATION,
project.getPath(),
null,
this::configureExtension);
threadRecorder.record(
ExecutionType.BASE_PLUGIN_PROJECT_TASKS_CREATION,
project.getPath(),
null,
this::createTasks);
}
上面只展示了BasePlugin的apply方法的部分代码,可以看到该方法会依次调用configureExtension、createTasks方法,下面就来看看configureExtension的部分代码(即第三步):
private void configureExtension() {
final NamedDomainObjectContainer<BuildType> buildTypeContainer =
project.container(
BuildType.class,
new BuildTypeFactory(instantiator, project, extraModelInfo));
final NamedDomainObjectContainer<ProductFlavor> productFlavorContainer =
project.container(
ProductFlavor.class,
new ProductFlavorFactory(
instantiator, project, project.getLogger(), extraModelInfo));
final NamedDomainObjectContainer<SigningConfig> signingConfigContainer =
project.container(SigningConfig.class, new SigningConfigFactory(instantiator));
final NamedDomainObjectContainer<BaseVariantOutput> buildOutputs =
project.container(BaseVariantOutput.class);
project.getExtensions().add("buildOutputs", buildOutputs);
extension =
createExtension(
project,
projectOptions,
instantiator,
androidBuilder,
sdkHandler,
buildTypeContainer,
productFlavorContainer,
signingConfigContainer,
buildOutputs,
extraModelInfo);
ndkHandler =
new NdkHandler(
project.getRootDir(),
null, /* compileSkdVersion, this will be set in afterEvaluate */
"gcc",
"" /*toolchainVersion*/,
false /* useUnifiedHeaders */);
@Nullable
FileCache buildCache = BuildCacheUtils.createBuildCacheIfEnabled(project, projectOptions);
GlobalScope globalScope =
new GlobalScope(
project,
projectOptions,
androidBuilder,
extension,
sdkHandler,
ndkHandler,
registry,
buildCache);
variantFactory = createVariantFactory(globalScope, instantiator, androidBuilder, extension);
taskManager =
createTaskManager(
globalScope,
project,
projectOptions,
androidBuilder,
dataBindingBuilder,
extension,
sdkHandler,
ndkHandler,
registry,
threadRecorder);
variantManager =
new VariantManager(
globalScope,
project,
projectOptions,
androidBuilder,
extension,
variantFactory,
taskManager,
threadRecorder);
......
}
可以看到configureExtension方法首先会创建下面的四个容器:
1> buildTypeContainer : 用于管理BuildType类型对象的容器。
2> productFlavorContainer:用于管理ProductFlavor类型对象的容器。
3> signingConfigContainer:用于管理SigningConfig类型对象的容器。
4> buildOutputs:用于管理BaseVariantOutput类型对象的容器。
接着依次创建extension、taskManager、variantManager对象:
1> extension对象的创建:调用AppPlugin的createExtension方法:
protected BaseExtension createExtension(
@NonNull Project project,
@NonNull ProjectOptions projectOptions,
@NonNull Instantiator instantiator,
@NonNull AndroidBuilder androidBuilder,
@NonNull SdkHandler sdkHandler,
@NonNull NamedDomainObjectContainer<BuildType> buildTypeContainer,
@NonNull NamedDomainObjectContainer<ProductFlavor> productFlavorContainer,
@NonNull NamedDomainObjectContainer<SigningConfig> signingConfigContainer,
@NonNull NamedDomainObjectContainer<BaseVariantOutput> buildOutputs,
@NonNull ExtraModelInfo extraModelInfo) {
return project.getExtensions()
.create(
"android",
AppExtension.class,
project,
projectOptions,
instantiator,
androidBuilder,
sdkHandler,
buildTypeContainer,
productFlavorContainer,
signingConfigContainer,
buildOutputs,
extraModelInfo);
}
该方法首先会获取到project中的ExtensionContainer类型的容器对象,然后调用该容器对象的create方法创建一个名称为android的AppExtension类型对象(使用上面创建的buildTypeContainer、productFlavorContainer、signingConfigContainer和buildOutputs进行创建)并且将android对象添加到该容器对象中,现在回头看看Demo项目中app module的build.gradle文件:
上图红框中的代码就是用来初始化android对象的。
2> taskManager对象的创建:调用AppPlugin的createTaskManager方法:
protected TaskManager createTaskManager(
@NonNull GlobalScope globalScope,
@NonNull Project project,
@NonNull ProjectOptions projectOptions,
@NonNull AndroidBuilder androidBuilder,
@NonNull DataBindingBuilder dataBindingBuilder,
@NonNull AndroidConfig androidConfig,
@NonNull SdkHandler sdkHandler,
@NonNull NdkHandler ndkHandler,
@NonNull ToolingModelBuilderRegistry toolingRegistry,
@NonNull Recorder recorder) {
return new ApplicationTaskManager(
globalScope,
project,
projectOptions,
androidBuilder,
dataBindingBuilder,
androidConfig,
sdkHandler,
toolingRegistry,
recorder);
}
可以看到taskManager是ApplicationTaskManager类型的对象,ApplicationTaskManager用于创建和管理com.android.application类型project(即build.gradle中有apply plugin: 'com.android.application'这句话的project)中的Task。
3> variantManager对象的创建:该对象用于创建和管理Build Variants。
接着分析时序图中的第4步,调用BasePlugin的createTasks方法:
private void createTasks() {
threadRecorder.record(
ExecutionType.TASK_MANAGER_CREATE_TASKS,
project.getPath(),
null,
() ->
taskManager.createTasksBeforeEvaluate(
new TaskContainerAdaptor(project.getTasks())));
project.afterEvaluate(
project ->
threadRecorder.record(
ExecutionType.BASE_PLUGIN_CREATE_ANDROID_TASKS,
project.getPath(),
null,
() -> createAndroidTasks(false)));
}
该方法通过调用project的afterEvaluate方法来添加一个闭包,该闭包会在project执行完成后(即project的build.gardle脚本执行完)被调用。
接着看第5步,BasePlugin的createAndroidTasks方法被执行,该方法会执行variantManager的createAndroidTasks方法(即第6步):
/**
* Variant/Task creation entry point.
*
* Not used by gradle-experimental.
*/
public void createAndroidTasks() {
......
for (final VariantScope variantScope : variantScopes) {
recorder.record(
ExecutionType.VARIANT_MANAGER_CREATE_TASKS_FOR_VARIANT,
project.getPath(),
variantScope.getFullVariantName(),
() -> createTasksForVariantData(tasks, variantScope));
}
taskManager.createReportTasks(tasks, variantScopes);
}
可以看到该方法会调用为每一个Build Variants调用createTasksForVariantData方法(即第7步), createTasksForVariantData方法用于为指定的Build Variants创建Task,createTasksForVariantData方法会调用ApplicationTaskManager的createTasksForVariantScope方法(即第8步):
@Override
public void createTasksForVariantScope(
@NonNull final TaskFactory tasks, @NonNull final VariantScope variantScope) {
BaseVariantData variantData = variantScope.getVariantData();
assert variantData instanceof ApplicationVariantData;
createAnchorTasks(tasks, variantScope);
createCheckManifestTask(tasks, variantScope);
handleMicroApp(tasks, variantScope);
// Create all current streams (dependencies mostly at this point)
createDependencyStreams(tasks, variantScope);
// Add a task to publish the applicationId.
createApplicationIdWriterTask(tasks, variantScope);
// Add a task to process the manifest(s)
recorder.record(
ExecutionType.APP_TASK_MANAGER_CREATE_MERGE_MANIFEST_TASK,
project.getPath(),
variantScope.getFullVariantName(),
() -> createMergeApkManifestsTask(tasks, variantScope));
// Add a task to create the res values
recorder.record(
ExecutionType.APP_TASK_MANAGER_CREATE_GENERATE_RES_VALUES_TASK,
project.getPath(),
variantScope.getFullVariantName(),
() -> createGenerateResValuesTask(tasks, variantScope));
// Add a task to compile renderscript files.
recorder.record(
ExecutionType.APP_TASK_MANAGER_CREATE_CREATE_RENDERSCRIPT_TASK,
project.getPath(),
variantScope.getFullVariantName(),
() -> createRenderscriptTask(tasks, variantScope));
// Add a task to merge the resource folders
recorder.record(
ExecutionType.APP_TASK_MANAGER_CREATE_MERGE_RESOURCES_TASK,
project.getPath(),
variantScope.getFullVariantName(),
(Recorder.VoidBlock) () -> createMergeResourcesTask(tasks, variantScope, true));
// Add a task to merge the asset folders
recorder.record(
ExecutionType.APP_TASK_MANAGER_CREATE_MERGE_ASSETS_TASK,
project.getPath(),
variantScope.getFullVariantName(),
() -> createMergeAssetsTask(tasks, variantScope, null));
// Add a task to create the BuildConfig class
recorder.record(
ExecutionType.APP_TASK_MANAGER_CREATE_BUILD_CONFIG_TASK,
project.getPath(),
variantScope.getFullVariantName(),
() -> createBuildConfigTask(tasks, variantScope));
recorder.record(
ExecutionType.APP_TASK_MANAGER_CREATE_PROCESS_RES_TASK,
project.getPath(),
variantScope.getFullVariantName(),
() -> {
// Add a task to process the Android Resources and generate source files
createApkProcessResTask(tasks, variantScope);
// Add a task to process the java resources
createProcessJavaResTask(tasks, variantScope);
});
recorder.record(
ExecutionType.APP_TASK_MANAGER_CREATE_AIDL_TASK,
project.getPath(),
variantScope.getFullVariantName(),
() -> createAidlTask(tasks, variantScope));
recorder.record(
ExecutionType.APP_TASK_MANAGER_CREATE_SHADER_TASK,
project.getPath(),
variantScope.getFullVariantName(),
() -> createShaderTask(tasks, variantScope));
// Add NDK tasks
if (!isComponentModelPlugin()) {
recorder.record(
ExecutionType.APP_TASK_MANAGER_CREATE_NDK_TASK,
project.getPath(),
variantScope.getFullVariantName(),
() -> createNdkTasks(tasks, variantScope));
} else {
if (variantData.compileTask != null) {
variantData.compileTask.dependsOn(getNdkBuildable(variantData));
} else {
variantScope.getCompileTask().dependsOn(tasks, getNdkBuildable(variantData));
}
}
variantScope.setNdkBuildable(getNdkBuildable(variantData));
// Add external native build tasks
recorder.record(
ExecutionType.APP_TASK_MANAGER_CREATE_EXTERNAL_NATIVE_BUILD_TASK,
project.getPath(),
variantScope.getFullVariantName(),
() -> {
createExternalNativeBuildJsonGenerators(variantScope);
createExternalNativeBuildTasks(tasks, variantScope);
});
// Add a task to merge the jni libs folders
recorder.record(
ExecutionType.APP_TASK_MANAGER_CREATE_MERGE_JNILIBS_FOLDERS_TASK,
project.getPath(),
variantScope.getFullVariantName(),
() -> createMergeJniLibFoldersTasks(tasks, variantScope));
// Add data binding tasks if enabled
createDataBindingTasksIfNecessary(tasks, variantScope);
// Add a compile task
recorder.record(
ExecutionType.APP_TASK_MANAGER_CREATE_COMPILE_TASK,
project.getPath(),
variantScope.getFullVariantName(),
() -> addCompileTask(tasks, variantScope));
createStripNativeLibraryTask(tasks, variantScope);
if (variantScope.getOutputScope().getMultiOutputPolicy().equals(MultiOutputPolicy.SPLITS)) {
if (extension.getBuildToolsRevision().getMajor() < 21) {
throw new RuntimeException(
"Pure splits can only be used with buildtools 21 and later");
}
recorder.record(
ExecutionType.APP_TASK_MANAGER_CREATE_SPLIT_TASK,
project.getPath(),
variantScope.getFullVariantName(),
() -> createSplitTasks(tasks, variantScope));
}
recorder.record(
ExecutionType.APP_TASK_MANAGER_CREATE_PACKAGING_TASK,
project.getPath(),
variantScope.getFullVariantName(),
() -> {
AndroidTask<BuildInfoWriterTask> buildInfoWriterTask =
createInstantRunPackagingTasks(tasks, variantScope);
createPackagingTask(tasks, variantScope, buildInfoWriterTask);
});
// create the lint tasks.
recorder.record(
ExecutionType.APP_TASK_MANAGER_CREATE_LINT_TASK,
project.getPath(),
variantScope.getFullVariantName(),
() -> createLintTasks(tasks, variantScope));
}
前面说过,ApplicationTaskManager用于创建和管理com.android.application类型project(即build.gradle中有apply plugin: 'com.android.application'这句话的project)中的Task,上面的方法就是用来创建Task的;在Gradle系列一 -- Groovy、Gradle和自定义Gradle插件中,我曾经打印过Build Android Project时依次执行的Task:
chenyangdeMacBook-Pro:HotFix chenyang$ ./gradlew app:aFreeWandoujiaR | grep executing
executing: preBuild
executing: extractProguardFiles
executing: preFreeWandoujiaReleaseBuild
executing: compileFreeWandoujiaReleaseAidl
executing: compileFreeWandoujiaReleaseRenderscript
executing: checkFreeWandoujiaReleaseManifest
executing: generateFreeWandoujiaReleaseBuildConfig
executing: prepareLintJar
executing: generateFreeWandoujiaReleaseResValues
executing: generateFreeWandoujiaReleaseResources
executing: mergeFreeWandoujiaReleaseResources
executing: createFreeWandoujiaReleaseCompatibleScreenManifests
executing: processFreeWandoujiaReleaseManifest
executing: splitsDiscoveryTaskFreeWandoujiaRelease
executing: processFreeWandoujiaReleaseResources
executing: generateFreeWandoujiaReleaseSources
executing: javaPreCompileFreeWandoujiaRelease
executing: compileFreeWandoujiaReleaseJavaWithJavac
executing: compileFreeWandoujiaReleaseNdk
executing: compileFreeWandoujiaReleaseSources
executing: mergeFreeWandoujiaReleaseShaders
executing: compileFreeWandoujiaReleaseShaders
executing: generateFreeWandoujiaReleaseAssets
executing: mergeFreeWandoujiaReleaseAssets
executing: processFreeWandoujiaReleaseJavaRes
executing: transformResourcesWithMergeJavaResForFreeWandoujiaRelease
executing: transformClassesAndResourcesWithProguardForFreeWandoujiaRelease
executing: transformClassesWithDexForFreeWandoujiaRelease
executing: mergeFreeWandoujiaReleaseJniLibFolders
executing: transformNativeLibsWithMergeJniLibsForFreeWandoujiaRelease
executing: transformNativeLibsWithStripDebugSymbolForFreeWandoujiaRelease
executing: packageFreeWandoujiaRelease
executing: lintVitalFreeWandoujiaRelease
executing: assembleFreeWandoujiaRelease
chenyangdeMacBook-Pro:HotFix chenyang$
上面执行的Task中的大部分都是通过ApplicationTaskManager的createTasksForVariantScope方法中创建的。
在Gradle系列一 -- Groovy、Gradle和自定义Gradle插件中讲到了Transform,com.android.application插件中是如何创建Transform相关的Task的呢?既然Transform是用来处理.class文件的,那么我就猜测是在addCompileTask方法中被创建的(即第9步),addCompileTask方法中会调用createPostCompilationTasks方法(即第10步):
/**
* Creates the post-compilation tasks for the given Variant.
*
* These tasks create the dex file from the .class files, plus optional intermediary steps like
* proguard and jacoco
*/
public void createPostCompilationTasks(
@NonNull TaskFactory tasks,
@NonNull final VariantScope variantScope) {
......
AndroidConfig extension = variantScope.getGlobalScope().getExtension();
// Merge Java Resources.
createMergeJavaResTransform(tasks, variantScope);
// ----- External Transforms -----
// apply all the external transforms.
List<Transform> customTransforms = extension.getTransforms();
List<List<Object>> customTransformsDependencies = extension.getTransformsDependencies();
for (int i = 0, count = customTransforms.size(); i < count; i++) {
Transform transform = customTransforms.get(i);
List<Object> deps = customTransformsDependencies.get(i);
transformManager
.addTransform(tasks, variantScope, transform)
.ifPresent(t -> {
if (!deps.isEmpty()) {
t.dependsOn(tasks, deps);
}
// if the task is a no-op then we make assemble task depend on it.
if (transform.getScopes().isEmpty()) {
variantScope.getAssembleTask().dependsOn(tasks, t);
}
});
}
......
}
由该方法的注释可知,该方法创建的所有Task(即所有以transform开头命名的Task)是用来将所有的.class文件转化成dex文件的,上面代码中的for循环就是用来为我们自定义并且注册的所有Transform创建对应的Task,关于怎么自定义和注册Transform,大家可以参考Gradle系列一 -- Groovy、Gradle和自定义Gradle插件。