天天看點

Cannot set the value of read-only property 'outputFile' for ApkVariantOutputImpl_Decorated

之前在舊版本Android Studio中用以下代碼修改過release版本的apk名:

applicationVariants.all { variant -> 
    variant.outputs.each { output ->
        def SEP = "_"
        def flavor = variant.productFlavors[].name
        def buildType = 
        variant.variantData.variantConfiguration.buildType.name
        def version = variant.versionName
        def date = new Date()
        def formattedDate = date.format('ddMMyy_HHmm')
        def newApkName = PROJECT_NAME + SEP + flavor + SEP + buildType + SEP + version + SEP + formattedDate + ".apk"
        def file = new File(newApkName)
        output.outputFile = file
    }
} 
           

然而更新Android Studio 3.0 後編譯不通過,并報了以下錯誤:

Cannot set the value of read-only property ‘outputFile’ for ApkVariantOutputImpl_Decorated{apkData=Main{type=MAIN, fullName=debug, filters=[]}} of type com.android.build.gradle.internal.api.ApkVariantOutputImpl.

原因

Android Studio 3.0 修改了打包規則,詳細規則見 Android plugin 3.0 migration guide(需翻牆)

解決方法

  • 使用 all() 替換 each()
  • 使用 outputFileName 替換 output.outputFile

示例

// If you use each() to iterate through the variant objects,
// you need to start using all(). That's because each() iterates
// through only the objects that already exist during configuration time—
// but those object don't exist at configuration time with the new model.
// However, all() adapts to the new model by picking up object as they are
// added during execution.
android.applicationVariants.all { variant ->
    variant.outputs.all {
        outputFileName = "${variant.name}-${variant.versionName}.apk"
    }
}
           

參考連結:

https://stackoverflow.com/questions/44239235/android-gradle-3-0-0-alpha2-plugin-cannot-set-the-value-of-read-only-property