Gradle常用配置

多渠道打包

上线一款app后需要统计分析各个渠道的使用数据,这就需要对渠道进行标示,这里以友盟统计为例

  • 在AndroidManifest中加入占位符
<meta-data
    android:name="UMENG_CHANNEL"
    android:value="${UMENG_CHANNEL}"/>
  • 在module的build.gradle中加入
android {
    defaultConfig {
        applicationId "com.linkzhang.gradlesample"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        manifestPlaceholders = [UMENG_CHANNEL: "example"]//默认渠道
    } //自动多渠道打包
    
    productFlavors {
        xiaomi {}
        _360 {}
        baidu {}
        wandoujia {}
        // 添加其它渠道
    }
 
    productFlavors.all {
        flavor -> flavor.manifestPlaceholders = [UMENG_CHANNEL: name]
    }
}

自动签名apk

使用命令行进行打包,需要读取签名配置并自动对apk进行签名

  • 在module的根目录下新建signing.properties文件
STORE_FILE = /keystore.jks
STORE_PASSWORD = 123456KEY_ALIAS = example
KEY_PASSWORD = 123456
  • 在module的build.gradle中创建
android {
    signingConfigs {
        debug {
    
        }
    
        release {
            storeFile
            storePassword
            keyAlias
            keyPassword
        }
    }
}
  • 读取配置文件
android {
    signingConfigs {
        debug {
        }
        
        release {
            storeFile
            storePassword
            keyAlias
            keyPassword
        }
    }

    // 读取签名配置文件
    getSigningProperties()
}

def getSigningProperties() 
{
    def propFile = file('signing.properties')    
    if (propFile.canRead()) 
    {
        def Properties props = new Properties()
        props.load(new FileInputStream(propFile))
        
        if (props!=null && props.containsKey('STORE_FILE') &&
            props.containsKey('STORE_PASSWORD') &&
            props.containsKey('KEY_ALIAS') &&
            props.containsKey('KEY_PASSWORD')) 
        {
            android.signingConfigs.release.storeFile = file(props['STORE_FILE'])
            android.signingConfigs.release.storePassword = props['STORE_PASSWORD']
            android.signingConfigs.release.keyAlias = props['KEY_ALIAS']
            android.signingConfigs.release.keyPassword = props['KEY_PASSWORD']
        } 
        else
        {
            println 'signing.properties found but some entries are missing'
            android.buildTypes.release.signingConfig = null
        }
    }
    else
    {
        println 'signing.properties not found'
        android.buildTypes.release.signingConfig = null
    }
}
  • 更改release设置
android {
    buildTypes {
        release {
            minifyEnabled true //开启代码混淆
            zipAlignEnabled true
            shrinkResources true // 移除无用的resource文件
            signingConfig signingConfigs.release
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
}

版本号自增

每次编译release版本时,版本号自动增加

  • 在module的根目录下新建version.properties文件
VERSION_CODE=1
  • 读取版本号
def getVersionCode() 
{
    def versionFile = file('version.properties')
    
    if (versionFile.canRead())
    {
        def Properties versionProps = new Properties()
        versionProps.load(new FileInputStream(versionFile))
        def versionCode = versionProps['VERSION_CODE'].toInteger()
        def runTasks = gradle.startParameter.taskNames //仅在assembleRelease任务是增加版本号
        if ('assembleRelease' in runTasks)
        {
            versionProps['VERSION_CODE'] = (++versionCode).toString()
            versionProps.store(versionFile.newWriter(), null)
        }

        return versionCode
    }
    else
    {
        throw new GradleException("Could not find version.properties!")
    }
}
  • 修改defaultConfig
android 
{    
    def currentVersionCode = getVersionCode()

    defaultConfig {
        applicationId "com.linkzhang.gradlesample"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode currentVersionCode
        versionName "1.0"
        manifestPlaceholders = [UMENG_CHANNEL_VALUE: "example"] //默认渠道
    }
}

自定义apk名称

导出的apk以app名版本号打包时间_渠道名_release.apk格式命名

  • 获取app名称和当前时间
// 获取当前系统时间
def releaseTime() 
{   
    return new Date().format("yyyy-MM-dd", TimeZone.getTimeZone("UTC"))
}

// 获取程序名称
def getProductName()
{
    return "gradlesample"
}
  • 替换文件名
android {
    buildType {  
        release {
            //修改生成的apk名字,格式为 app名_版本号_打包时间_渠道名_release.apk
            applicationVariants.all { variant ->
                variant.outputs.each { output ->       
                    def oldFile = output.outputFile
                    if (variant.buildType.name.equals('release')) 
                    {
                        def releaseApkName = getProductName() + "_v${defaultConfig.versionName}_${releaseTime()}_" + variant.productFlavors[0].name + '_release.apk'
                            
                        output.outputFile = new File(oldFile.parent, releaseApkName)
                    }
                }
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/zxsean/article/details/106381178