Android 为生成的apk文件名加上时间,修改java类中的代码

本文介绍如何在Android项目中通过修改build.gradle文件,使生成的APK文件名包含当前时间戳,以实现每次打包时文件名的独特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

不多说直接上代码(build.gradle 代码):关键地方都有注释

buildscript {
    repositories {
        jcenter();
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'
    }
}

println("I'm now compiling with gradle " + project.gradle.gradleVersion);
apply plugin: 'com.android.application'

dependencies {
    compile fileTree(include: '*.jar', dir: 'libs')
    compile 'com.android.support:multidex:1.0.1'
}

//获取当前时间
def releaseTime() {
    return new Date().format("yyyy-MM-dd HH.mm.ss", TimeZone.getTimeZone("GMT+08:00"))
}

//读取文件中的字符串并替换
def fileReader(path, oldStr, newStr) {
    def readerString = "";
    new File(path).withReader('UTF-8') { reader ->
        reader.eachLine {
            if (it.find(oldStr)) {
                it = it.replace(oldStr, newStr)
            }
            readerString <<= it
            readerString << '\n'
        }
        return readerString
    }
}

//写文件
def fileWrite(path, stringBuffer) {
    new File(path).withWriter('UTF-8') {
        within ->
            within.append(stringBuffer)
    }
}

android {
    compileSdkVersion 22
    buildToolsVersion '23.0.2'

    defaultConfig {
        applicationId "com.***.***"
        minSdkVersion 14
        targetSdkVersion 22
        versionCode 1
        versionName "1.0.0"
        multiDexEnabled true;
    }

    packagingOptions {
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/LICENSE.txt'
    }

    //把 ***.***.Version.java 类中的version变量从“TEST”变为“PRODUCT”
    task replaceToProduct << {
        def strBuffer = fileReader(rootDir.getAbsolutePath() + '\\src\\***\\***\\Version.java',
                "public static final String version = TEST",
                "public static final String version = PRODUCT");
        fileWrite(rootDir.getAbsolutePath() + '\\src\\***\\***\\Version.java', strBuffer);
    }

   //把 ***.***.Version.java 类中的version变量从“PRODUCT”变为“TEST”
    task replaceToTest << {
        def strBuffer = fileReader(rootDir.getAbsolutePath() + '\\src\\***\\***\\Version.java',
                "public static final String version = PRODUCT",
                "public static final String version = TEST");
        fileWrite(rootDir.getAbsolutePath() + '\\src\\***\\***\\Version.java', strBuffer);
    }

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }

        // Move the tests to tests/java, tests/res, etc...
        instrumentTest.setRoot('tests')

        // Move the build types to build-types/<type>
        // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...
        // This moves them out of them default location under src/<type>/... which would
        // conflict with src/ being used by the main source set.
        // Adding new build types or product flavors should be accompanied
        // by a similar customization.
        debug.setRoot('build-types/debug')
        release.setRoot('build-types/release')
        //新增“releaseTest”BuildType类型
        releaseTest.setRoot('build-types/releaseTest');
    }

    lintOptions {
        abortOnError false
        disable 'MissingTranslation'
    }

    //签名
    signingConfigs {
        debug {
            storeFile file("***.keystore")
            storePassword "keystore_password"
            keyAlias "alias"
            keyPassword "alias_password"
        }
        release {
            storeFile file("***.keystore")
            storePassword "keystore_password"
            keyAlias "alias"
            keyPassword "alias_password"
        }
    }
    buildTypes {
//        debug {
//            // 显示Log
            buildConfigField "boolean", "LOG_DEBUG", "true"
//
//            versionNameSuffix "-debug"
//            minifyEnabled false
//            zipAlignEnabled false
//            shrinkResources false
//            signingConfig signingConfigs.debug
//        }
        release {
            // 不显示Log
//            buildConfigField "boolean", "LOG_DEBUG", "false"
            versionNameSuffix "-release"
            minifyEnabled true //混淆
            zipAlignEnabled true //Zipalign优化
            shrinkResources true // 移除无用的resource文件
            //加载混淆配置文件
            proguardFiles 'proguard-project.txt'
            //签名
            signingConfig signingConfigs.release
        }

        //新增“releaseTest”BuildType类型
        //可以用已有类型(buildTypes.release)初始化,也可以直接添加属性写闭合。
        releaseTest.initWith(buildTypes.release)
        releaseTest {

        }
    }

//    compileOptions {
//        sourceCompatibility JavaVersion.VERSION_1_7
//        targetCompatibility JavaVersion.VERSION_1_7
//    }

    //自定义打包生成的apk的文件名,当BuildType类型是“release”和“releaseTest”类型时才改变。
    applicationVariants.all { variant ->
        if(variant.buildType.name.equals("release")||variant.buildType.name.equals("releaseTest")){
            variant.outputs.each { output ->
                def outputFileDir="./"
                def outputFile = output.outputFile
                if (outputFile != null && outputFile.name.endsWith('.apk')) {
//                def fileName = outputFile.name.replace(".apk", "-${defaultConfig.versionName}.apk")
                    if(variant.buildType.name.equals("release")){
                        def fileName = "release_product_${defaultConfig.versionName}_${releaseTime()}.apk"
                        output.outputFile = new File(outputFileDir,fileName)
                    }else if(variant.buildType.name.equals("releaseTest")){
                        def fileName = "release_test_${defaultConfig.versionName}_${releaseTime()}.apk"
                        output.outputFile = new File(outputFileDir,fileName)
                    }
                }
            }
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值