避免gradle构建参数进行干净的任务

时间:2018-11-21 09:22:53

标签: android android-studio gradle android-gradle build.gradle

我将我的应用程序级别 build.gradle 文件配置为从构建参数中选择apk名称。

下面是我的build.gradle文件

class Demo{
    const RESULT_OF_SEARCH_POSITIVE = "positive";
    const RESULT_OF_SEARCH_NEGATIVE = "negative";
    const RESULT_OF_SEARCH_PARTLY = "partly";

function calculateResultOfSearch(array $imagesResultArray)
{
  if (count(array_count_values($imagesResultArray)) == 1 && $imagesResultArray[0] === self::RESULT_OF_SEARCH_POSITIVE) {
   return current($imagesResultArray);
} elseif(count(array_count_values($imagesResultArray)) == 1 && $imagesResultArray[0]== self::RESULT_OF_SEARCH_NEGATIVE) {
  return self::RESULT_OF_SEARCH_NEGATIVE;
} else {
  return self::RESULT_OF_SEARCH_PARTLY;
   }
  }
}

$demo = new Demo();    
print_r($demo->calculateResultOfSearch(["positive","positive"]));

现在我可以发出以下命令来构建具有自定义名称的apk

array_count_values()

但是问题是如果我必须清理apk,我必须将构建参数传递给clean命令

以下命令失败

array_count_values

以下命令运行正常

apply plugin: 'com.android.application'
android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.somethind"
        minSdkVersion 16
        targetSdkVersion 25
        ....
    }

    applicationVariants.all { variant ->
        changeAPKName(variant, project.apkName)
    }

    buildTypes {
        ......
        ......
    }
    repositories {
        flatDir {
            dirs 'libs'
        }
    }
}

def changeAPKName(variant, apkName) {
    variant.outputs.all { output ->
        outputFileName = new File(apkName)
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])

    ........
}

如何避免将构建参数传递给 clean 任务

1 个答案:

答案 0 :(得分:0)

这里的问题是我们需要为project.apkName提供一些默认值。因此,当我们没有从命令行传递apkName参数时,它将采用默认值。可以像下面这样

apply plugin: 'com.android.application'
android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.somethind"
        minSdkVersion 16
        targetSdkVersion 25
        ....
    }

    def defaultApkName = "Pervacio_ssd.apk"
    applicationVariants.all { variant ->
        if(project.hasProperty("apkName")){
            defaultApkName = apkName;
        }
        changeAPKName(variant, defaultApkName)
    }

    buildTypes {
        ......
        ......
    }
    repositories {
        flatDir {
            dirs 'libs'
        }
    }
}

def changeAPKName(variant, apkName) {
    variant.outputs.all { output ->
        outputFileName = new File(apkName)
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])

    ........
}