[原]Android打包之Gradle打包

最近嘗試了一下Android的Gradle打包,發現確實比Ant打包會方便不少,特此記錄下來。html

注:android的gradle如今插件的版本已是0.14.3了,對於一些老的方法和api,有一些已經被移除,沒法使用(http://tools.android.com/tech-docs/new-build-system/migrating-to-1-0-0),如下這些屬性更名,原先的不能用:java

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

一、將Eclipse project轉換成Gradle project:android

      在Project右鍵->Export->Generate Gradle build files,這樣就會在Project多出一下文件:git

  

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

gradlew和gradlew.bat分別是*nix下和windows下可執行的腳本,gradle-wrapper.properties用來指定須要下載的gradle的版本,內容以下:windows

#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是用來配置編譯選項的文件,附一個可以成功運行的編譯腳本:api

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進行打包便可,輸出以下結果就表示打包成功:app

: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
相關文章
相關標籤/搜索