欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android Studio3.0以后outputfile不可用更改

程序员文章站 2022-04-24 14:24:36
...

Android Studio自从更新3.0,gradle更新3.1.3之后,build.gradle文件中outputfile就不可用了,会报错,既Cannot set the value of read-only property 'outputFile' for object of type com.android.build.gradle.internal.api.LibraryVariantOutputImpl.
报错如下:
Android Studio3.0以后outputfile不可用更改
所以如果要打包aar,使用自定义路径和文件名称,需要使用新的方法。
如果使用:

apply plugin: 'com.android.library'

就是打包aar。
以下是具体的代码,可以直接使用。直接放在build.gradle文件最外面即可使用

android.libraryVariants.all { variant ->
    variant.outputs.all {
        // 自定义输出路径
	// variant.getPackageApplication().outputDirectory = new File("C:\\1")
        // 自定义文件名{示例:AppName-Flavor-debug-v1.0.0_201807301409}
        outputFileName = "test.aar"
    }
}
//挂接自定义task到构建过程中
this.project.afterEvaluate { project ->
//    获得build task
    def buildTask = project.tasks.getByName('build')
    if (buildTask == null) {
        throw GradleException('the build task is not found')
    }
    buildTask.doLast {
        copyTask.execute()
    }
}
//自定义copyApk task
task copyTask {
    doLast {
        def fileName = "test.aar"
//        拷贝文件的始发地
        def sourceFile = "/build/outputs/aar/" + fileName
//        指定文件拷贝的目的地
        def destationFile = new File("C:\\1 ")
        try {
//            判断文件夹是否存在
            if (!destationFile.exists()) {
                destationFile.mkdir()
            }
            //拷贝
            copy {
                from sourceFile
                into destationFile
                rename {
                    fileName
                }
            }
        } catch (Exception e) {
            e.printStackTrace()
        }
    }
}

上面build之后就在c:\1目录下面去查找对应的aar即可
当然如果使用

apply plugin: 'com.android.application'

就更简单了,直接在最外围放以下代码即可

android.applicationVariants.all { variant ->
    variant.outputs.all {
        // 自定义输出路径
        variant.getPackageApplication().outputDirectory = new File("C:\\1")
        // 自定义文件名{示例:AppName-Flavor-debug-v1.0.0_201807301409}
        outputFileName = "test.aar"
    }
}