Gradle 4.4中如何将APK从构建目录复制到指定位置?
Solution to Copy APKs to Custom Location in Gradle 4.4
Hey there! I totally get the hassle with Gradle 4.4's restrictions—you can't directly modify the APK output path or use absolute paths for it, and tweaking variant outputs during build isn't feasible either. Let's implement that post-build copy task you found references to, step by step.
Here's how to integrate the copy logic into your existing Gradle script:
android { // ... your existing android config (compileSdkVersion, defaultConfig, etc.) ... android.applicationVariants.all { variant -> // Optional: Skip debug builds if you only care about release APKs if (variant.buildType.name == 'debug') { return } // Define your target output directory (adjust this path to your needs) def targetDir = file("$rootProject.projectDir/apk-distribution") // Ensure the directory exists before copying targetDir.mkdirs() // Grab all output APK files for the current variant def apkFiles = variant.outputs*.outputFile // Create a dedicated copy task for this variant def copyApkTask = tasks.create(name: "copy${variant.name.capitalize()}Apk", type: Copy) { from apkFiles into targetDir // Optional: Rename the APK to a more readable format rename { originalName -> "MyApp-${variant.buildType.name}-v${variant.versionName}.apk" } } // Make sure the copy runs only after the APK is fully built copyApkTask.dependsOn variant.assemble // Auto-run the copy task when you build the variant (e.g., assembleRelease) tasks.getByName("assemble${variant.name.capitalize()}").finalizedBy copyApkTask } }
Key Details Breakdown:
- Target Path Flexibility: You can replace
$rootProject.projectDir/apk-distributionwith any path you want—absolute paths likefile("/Users/your-name/Documents/apk-builds")work perfectly here. - Variant Control: The debug build check lets you focus on release APKs; remove that block if you want to copy debug builds too.
- Task Dependencies:
dependsOnensures the copy won't run until the APK is assembled, andfinalizedByties the copy task directly to the variant's build command (so you don't have to run a separate task manually). - Custom Naming: The
renameblock gives you control over the APK filename—adjust it to include build numbers, flavors, or any other details you need.
To test this, just run your usual build command (like ./gradlew assembleRelease). Once the build finishes, your APK will be waiting in the target directory you specified.
内容的提问来源于stack exchange,提问作者Kapil Rajput
相关产品推荐
相关产品推荐

