【原创】解决React Native报错:Cannot set the value of read-only property 'outputFile' for ApkVariantOutputImpl_Decorated

blogdaren 2018-07-18 抢沙发 2313人次

问题背景

同样是在升级 gradle plugin V2.2.3 --> gradle plugin V3.0.1后,行至打包APK期间

FAILURE: Build failed with an exception.

* Where:
Build file '/path/to/Project/android/app/build.gradle' line: 150

* What went wrong:
A problem occurred configuring project ':app'.
> 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.

问题原因

outputFile 属性是只读的,不可写。

错误姿势:

applicationVariants.all { variant ->
  variant.outputs.each { output ->
      // For each separate APK per architecture, set a unique version code as described here:
      // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
      def versionCodes = ["armeabi-v7a":1, "x86":2]
      def abi = output.getFilter(OutputFile.ABI)
      if (abi != null) {  // null for the universal-debug, universal-release variants
          output.versionCodeOverride =
                  versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
      }   
      def outputFile = output.outputFile
      if (outputFile != null && outputFile.name.endsWith('.apk')) {
          File outputDirectory = new File(outputFile.parent)
          def fileName
          if (variant.buildType.name == "release") {
              fileName = "jinniuzuo_v${defaultConfig.versionName}_${packageTime()}_release.apk"
          } else if (variant.buildType.name == "debug") {
              fileName = "jinniuzuo_v${defaultConfig.versionName}_${packageTime()}_debug.apk"
          }   
          output.outputFile = new File(outputDirectory, fileName)
      }   
  }
}  

正确姿势:

android.applicationVariants.all { variant ->
    variant.outputs.all {
        def date = new Date()
        def formattedDate = date.format('yyyyMMdd')
        def apkFileName
        
        if (variant.buildType.name == "debug") {
            //输出:jinniuzuo_v1.0_debug.apk
            apkFileName = "jinniuzuo_v${defaultConfig.versionName}_debug.apk"
        } else if (variant.buildType.name == "release") {
            //输出:jinniuzuo_v1.0_debug.apk
            apkFileName = "jinniuzuo_V${defaultConfig.versionName}_release.apk"
        } else {
            //输出:jinniuzuo_v1.0_2018-07-18.apk
            apkFileName = "jinniuzuo_v${defaultConfig.versionName}_${formattedDate}.apk"
        }

        outputapkFileName = apkFileName
    }
}

版权声明:除非注明,本文由( blogdaren )原创,转载请保留文章出处。

本文链接:【原创】解决React Native报错:Cannot set the value of read-only property 'outputFile' for ApkVariantOutputImpl_Decorated

发表评论:

您的昵称:
电子邮件:
个人主页: