android gradle 增加 lint

android gradle increment lint

因为我会在 Android 的增量 Lint 检查上工作,而且我看了一些文章,我发现我可以在 build.gradle 中添加一个任务,然后传入一些参数通过重写LintGradleClient,它应该按照文章中的描述工作,但是我按照文章中描述的,在增加LintGradle参数AndroidProject cannot be got,我这里使用kotlin achieve.Someone谁能帮帮我? 这里是文章url路径https://www.jianshu.com/p/4833a79e9396

我的代码在 get AndroidProject as Kotlin:

fun getAndroidProject(): AndroidProject{
   var gradleConn = GradleConnector.newConnector()
   gradleConn.forProjectDirectory(getProject().getProjectDir())  
   var modelProject =   gradleConn.connect().getModel(com.android.builder.model.AndroidProject::class.java)
   return modelProject
}

和我运行任务,它是这样告诉我的:

No model of type 'AndroidProject' is available in this build.

那篇文章android插件的版本是旧的,从3.0.0开始AndroidProject的获取方式变了

看完gradleandroid插件的源码,com.android.build.gradle.tasks.LintBaseTask给出了一个线索:

protected AndroidProject createAndroidProject(Project gradleProject) {
    String modelName = AndroidProject.class.getName();
    ToolingModelBuilder modelBuilder = this.toolingRegistry.getBuilder(modelName);

    assert modelBuilder != null;

    ExtraPropertiesExtension ext = gradleProject.getExtensions().getExtraProperties();
    ext.set("android.injected.build.model.only.versioned", Integer.toString(3));
    ext.set("android.injected.build.model.disable.src.download", Boolean.valueOf(true));

    AndroidProject var5;
    try {
        var5 = (AndroidProject)modelBuilder.buildAll(modelName, gradleProject);
    } finally {
        ext.set("android.injected.build.model.only.versioned", (Object)null);
        ext.set("android.injected.build.model.disable.src.download", (Object)null);
    }

    return var5;
}

继续前进,我们可以发现:
1. toolingRegistryGlobalScope.getToolingRegistry()
得到 2. GlobalScopeVariantScope.getGlobalScope()
得到 3. VariantScopeApplicationVariant.getVariantData().getScope()

得到

ApplicationVariantcom.android.application插件中applicationVariants的元素,可以遍历applicationVariants列表获取。

这是app/build.gradle中的示例代码:

android {
    // other script...

    applicationVariants.all { variant ->
        def globalScope = variant.variantData.scope.globalScope
        String modelName = AndroidProject.class.getName()
        ToolingModelBuilder modelBuilder = globalScope.toolingRegistry.getBuilder(modelName)
        AndroidProject androidProject = (AndroidProject) modelBuilder.buildAll(modelName, project)
        // create your task to do something
    }
}