You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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-distribution with any path you want—absolute paths like file("/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: dependsOn ensures the copy won't run until the APK is assembled, and finalizedBy ties the copy task directly to the variant's build command (so you don't have to run a separate task manually).
  • Custom Naming: The rename block 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:59:14