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

Android Gradle Plugin3.+下如何用Java修改APK名称?

Fixing APK Filename Modification in Java-written Gradle Plugin for AGP 3.1.2

I've dealt with this exact issue when migrating our team's Gradle plugins from Groovy to Java after upgrading to AGP 3.x. The core problem with your current code is that manually renaming the output file using renameTo() doesn't integrate with AGP's updated build model—Gradle might not detect this change, or AGP's internal tasks could overwrite your filename later in the process.

Instead, you should use AGP's official API to set the output filename directly, just like the Groovy example. Here's the corrected Java code:

import com.android.build.gradle.api.ApplicationVariant;
import com.android.build.gradle.internal.api.BaseVariantOutputImpl;

// ...

extension.getApplicationVariants().all(variant -> {
    variant.getOutputs().all(output -> {
        // Customize your filename pattern to match your needs
        String fileName = String.format("%s-%s.apk", 
            variant.getName(), 
            variant.getVersionName()
        );
        
        // Cast to BaseVariantOutputImpl to access the outputFileName property
        ((BaseVariantOutputImpl) output).getOutputFileName().set(fileName);
    });
});

Key Notes:

  • Use the official API instead of manual file edits: AGP 3.0+ provides an outputFileName property for each variant output. Setting this property tells AGP to use your custom filename during APK generation, which works seamlessly with Gradle's task graph and caching system. Manual file operations like renameTo() are unreliable because they bypass Gradle's task tracking.
  • Casting to BaseVariantOutputImpl: The public VariantOutput interface doesn't expose the getOutputFileName() method directly. Casting to the internal implementation class is the standard workaround in Java (Groovy avoids this via dynamic typing).
  • Customize the filename pattern: If you need to include the build type's version suffix, adjust the filename string like this:
    String fileName = String.format("%s-%s%s.apk", 
        variant.getName(), 
        variant.getVersionName(),
        variant.getBuildType().getVersionNameSuffix()
    );
    

Make sure your plugin's build.gradle includes the correct AGP dependency (e.g., compileOnly 'com.android.tools.build:gradle:3.1.2') to access these classes.

内容的提问来源于stack exchange,提问作者littlegnal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:13:40