编辑
有时候为了方便打包多个版本的apk,减少代码改动,我们会在gradle中设置很多product flavor和flavor dimension,但是设置的flavor或dimension太多,会产生gradle执行效率大幅降低的问题
本文访问次数:0
Sometimes we need to put a lot of configurations in gradle file,in order to build different apks.However, this could cause a serious gradle effiency issue,that is everything is fxxking slow,inlcuding gradle sync,gradle window fake dead and so on.It turns out we can ignore some tasks to make things a lot better!

下面是正文


通过使用忽略不相关task的方式,可以大大加快gradle sync的速度

例如应用有四种flavor

flavorDimensions "flavorA","flavorB","flavoC","flavorD"
productFlavors{
    flavorAA{
        dimension "flavorA"
    }
    flavorAB{
        dimension "flavorA"
    }
    flavorBA{
        dimension "flavorB"
    }
    flavorBB{
        dimension "flavorB"
    }
    flavorCA{
        dimension "flavorC"
    }
    flavorCB{
        dimension "flavorC"
    }
    flavorDA{
        dimension "flavorD"
    }
    flavorDB{
        dimension "flavorD"
    }
}

经过组合,一共有8种打包方式,16种build variants(包括debugrelease),这时候打包速度其实还可以接受

现在添加gradle脚本,忽略不相关task,首先在app模块的build.gradle添加代码,读取local.properties

Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())
def flavorAValue = properties.getProperty("flavorA")
def flavorBValue = properties.getProperty("flavorB")
def flavorCValue = properties.getProperty("flavorC")
def flavorDValue = properties.getProperty("flavorD")
if (flavorAValue == null)
    flavorAValue = 'flavorAA'
if (flavorBValue == null)
    flavorBValue = 'flavorBA'
if (flavorCValue == null)
    flavorCValue = 'flavorCA'
if (flavorDValue == null)
    flavorDValue = 'flavorDA'
def compositeFlavors = flavorAValue+flavorBValue+flavorCValue+flavorDValue

同样的文件,添加代码,忽略不相关task

android{
    android.variantFilter { variant ->
        if(!variant.getName().toUpperCase().startsWith(compositeFlavors.toUpperCase())){
            variant.setIgnore(true)
        }
    }
}

重新sync,将看到Build Variant窗口只剩下两个选项flavorAAflavorBAflavorCAflavorDADebug和flavorAAflavorBAflavorCAflavorDADebug,同理Gradle窗口下的选项也仅剩下flavorAAflavorBAflavorCAflavor相关的task

需要输入验证码才能留言

没有任何评论