[原]Android打包之Gradle打包

最近尝试了一下Android的Gradle打包,发现确实比Ant打包会方便很多,特此记录下来。

注:android的gradle现在插件的版本已经是0.14.3了,对于一些老的方法和api,有一些已经被移除,无法使用(http://tools.android.com/tech-docs/new-build-system/migrating-to-1-0-0),以下这些属性改名,原先的不能用:

runProguard -> minifyEnabled (是否混淆)
zipAlign -> zipALignEnabled (是否zip对齐)
packageName -> applicationId
jniDebugBuild-> jniDebuggable
renderscriptDebug->renderscriptDebuggable
renderscriptSupportMode->renderscriptSupportModeEnabled
renderscriptNdkMode->renderscriptNdkModeEnabled
Variant.packageApplication/zipAlign/createZipAlignTask/outputFile/processResources/processManifest使用variant.out代替

1、将Eclipse project转换成Gradle project:

      在Project右键->Export->Generate Gradle build files,这样就会在Project多出一下文件:

  

├── build.gradle
├── gradle
│   └── wrapper
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat

gradlew和gradlew.bat分别是*nix下和windows下可执行的脚本,gradle-wrapper.properties用来指定需要下载的gradle的版本,内容如下:

#Wed Apr 10 15:27:10 PDT 2013
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=http\://services.gradle.org/distributions/gradle-2.2.1-all.zip

build.gradle是用来配置编译选项的文件,附一个能够成功运行的编译脚本:

import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.regex.Pattern

buildscript {
    repositories {
        mavenCentral()
    }
    //指定gradle插件版本
    dependencies {
        classpath com.android.tools.build:gradle:0.14.+
    }
}
apply plugin: android

//添加android依赖libs
dependencies {
    compile fileTree(dir: libs, include: [*.jar])
}

//获取系统时间
def buildTime() {
       def df = new SimpleDateFormat("yyyyMMdd‘-‘HHmm")
       df.setTimeZone(TimeZone.getDefault())
       return df.format(new Date())
}

def apkName = "AndroidGradle"

android {
    compileSdkVersion 18
    buildToolsVersion "20.0.0"

    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)
    }
    
    //签名
    signingConfigs {
        release {
            storeFile file(release.keystore)
            storePassword 123456
            keyAlias demo
            keyPassword 111111
        }
    }
    
    //渠道
    productFlavors {
        free {
            applicationId com.clarck.httpclientnew.free
        }
        premium {
            applicationId com.clarck.httpclientnew.premium
        }
    }
    
    //lint检查
    lintOptions {
        abortOnError false
    }
    
    buildTypes {
        release {
            //混淆开关
            minifyEnabled true
            //是否zip对齐
            zipAlignEnabled true
            //是否打开debuggable开关
            debuggable false
            //是否打开jniDebuggable开关
            jniDebuggable false
            //混淆配置文件
            proguardFiles getDefaultProguardFile(proguard-android.txt)
            //签名配置
            signingConfig signingConfigs.release
        }
        
        android.applicationVariants.all { variant ->
            def manifestFile = file("AndroidManifest.xml")
            def pattern = Pattern.compile("versionName=\"(.+)\"")
            def manifestText = manifestFile.getText()
            def matcher = pattern.matcher(manifestText)
            matcher.find()
            def versionName = matcher.group(1)            
            pattern = Pattern.compile("versionCode=\"(.+)\"")
            matcher = pattern.matcher(manifestText)
            matcher.find()
            def versionCode = matcher.group(1)            
            
            if (variant.buildType.zipAlignEnabled) {  
                variant.outputs.each { output ->  
                    def outputFile = output.outputFile  
                    if (outputFile != null && outputFile.name.endsWith(.apk)) {  
                        def fileName = "apk/" + applicationId + "-V" + versionName + "-" + versionCode + "-" + variant.name + "-" + buildTime() + ".apk"  
                        output.outputFile = new File(outputFile.parent, fileName)  
                    }  
                }  
            } else {  
                variant.outputs.each { output ->  
                    def outputFile = output.outputFile  
                    if (outputFile != null && outputFile.name.endsWith(.apk)) {  
                        def fileName = "apk/" + applicationId + "-V" + versionName + "-" + versionCode + "-" + variant.name + "-" + buildTime() + "-unaligned.apk"  
                        output.outputFile = new File(outputFile.parent, fileName)  
                    }  
                }  
            }  
        }
    }
}

 最后执行./gradlew build进行打包即可,输出如下结果就表示打包成功:

:preBuild
:compileFreeDebugNdk
:preFreeDebugBuild
:checkFreeDebugManifest
:prepareFreeDebugDependencies
:compileFreeDebugAidl
:compileFreeDebugRenderscript
:generateFreeDebugBuildConfig
:generateFreeDebugAssets UP-TO-DATE
:mergeFreeDebugAssets
:generateFreeDebugResValues UP-TO-DATE
:generateFreeDebugResources
:mergeFreeDebugResources
:processFreeDebugManifest
:processFreeDebugResources
:generateFreeDebugSources
:compileFreeDebugJava
:preDexFreeDebug
:dexFreeDebug
:processFreeDebugJavaRes UP-TO-DATE
:validateDebugSigning
:packageFreeDebug
:zipalignFreeDebug
:assembleFreeDebug
:compilePremiumDebugNdk
:prePremiumDebugBuild
:checkPremiumDebugManifest
:preparePremiumDebugDependencies
:compilePremiumDebugAidl
:compilePremiumDebugRenderscript
:generatePremiumDebugBuildConfig
:generatePremiumDebugAssets UP-TO-DATE
:mergePremiumDebugAssets
:generatePremiumDebugResValues UP-TO-DATE
:generatePremiumDebugResources
:mergePremiumDebugResources
:processPremiumDebugManifest
:processPremiumDebugResources
:generatePremiumDebugSources
:compilePremiumDebugJava
:preDexPremiumDebug
:dexPremiumDebug
:processPremiumDebugJavaRes UP-TO-DATE
:packagePremiumDebug
:zipalignPremiumDebug
:assemblePremiumDebug
:assembleDebug
:preFreeReleaseBuild
:checkFreeReleaseManifest
:prepareFreeReleaseDependencies
:compileFreeReleaseAidl
:compileFreeReleaseRenderscript
:generateFreeReleaseBuildConfig
:generateFreeReleaseAssets UP-TO-DATE
:mergeFreeReleaseAssets
:generateFreeReleaseResValues UP-TO-DATE
:generateFreeReleaseResources
:mergeFreeReleaseResources
:processFreeReleaseManifest
:processFreeReleaseResources
:generateFreeReleaseSources
:compileFreeReleaseJava
:lintVitalFreeRelease
:compileFreeReleaseNdk
:proguardFreeRelease
:dexFreeRelease
:processFreeReleaseJavaRes UP-TO-DATE
:validateReleaseSigning
:packageFreeRelease
:zipalignFreeRelease
:assembleFreeRelease
:prePremiumReleaseBuild
:checkPremiumReleaseManifest
:preparePremiumReleaseDependencies
:compilePremiumReleaseAidl
:compilePremiumReleaseRenderscript
:generatePremiumReleaseBuildConfig
:generatePremiumReleaseAssets UP-TO-DATE
:mergePremiumReleaseAssets
:generatePremiumReleaseResValues UP-TO-DATE
:generatePremiumReleaseResources
:mergePremiumReleaseResources
:processPremiumReleaseManifest
:processPremiumReleaseResources
:generatePremiumReleaseSources
:compilePremiumReleaseJava
:lintVitalPremiumRelease SKIPPED
:compilePremiumReleaseNdk
:proguardPremiumRelease
:dexPremiumRelease
:processPremiumReleaseJavaRes UP-TO-DATE
:packagePremiumRelease
:zipalignPremiumRelease
:assemblePremiumRelease
:assembleRelease
:assemble
:compileLint
:lint
Ran lint on variant premiumRelease: 5 issues found
Ran lint on variant freeDebug: 5 issues found
Ran lint on variant premiumDebug: 5 issues found
Ran lint on variant freeRelease: 5 issues found
Wrote HTML report to file:/data/gitwork/AutoBuildProject/build/outputs/lint-results.html
Wrote XML report to /data/gitwork/AutoBuildProject/build/outputs/lint-results.xml
:check
:build

BUILD SUCCESSFUL

Total time: 41.892 secs

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。