android项目构建之gradle的配置(含范例代码)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lijizhi19950123/article/details/79343517

gradle的定义

Gradle 是一个基于Ant和Maven概念的项目自动化建构工具。它使用一种基于Groovy的特定领域语言(DSL)来声明项目设置,这比我们的ANT使用XML构建配置要灵活的多。在编写配置时,你可以像编程一样灵活,Gradle是基于Groovy的DSL语言,完全兼容JAVA。

gradle的相关文件

gradle的相关文件分别是根目录下的 build.gradle、settings.gradle 和 app 目录下的 build.gradle 文件

根目录下的build.gradle

其主要的作用是对project添加引用的仓库及插件的依赖等等,具体使用方法可以看我的范例代码

buildscript {
    //引用仓库
    repositories {
        mavenCentral()
        google()
        jcenter()
    }
    //添加插件的依赖
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
        //greendao相关插件配置
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'
        //butterknife相关插件配置
        classpath 'com.jakewharton:butterknife-gradle-plugin:8.5.1'
    }
}
//所有module通用的配置
allprojects {
    repositories {
        google()
        jcenter()
        maven { url "https://jitpack.io" }
    }
}

//统一依赖管理
ext {
    minSdkVersion = 19
    compileSdkVersion = 27
    targetSdkVersion = 22
    supportLibVersion = '27.0.2'
    multidexVersion = '1.0.2'
    butterknifeVersion = '8.8.1'
    glideVersion = '4.4.0'
    rxjava2Version = '2.1.7'
    rxandroidVersion = '2.0.1'
    retrofit2Version = '2.3.0'
    okhttpVersion = '3.9.1'
    greendaoVersion = '3.2.2'
    eventbusVersion = '3.1.1'
    loggerVersion = '2.1.1'

}
//定义一个task,作用是清除根目录下的build文件夹
task clean(type: Delete) {
    delete rootProject.buildDir
}

app 目录下的 build.gradle 文件

app下的build.gradle文件主要作用是对项目的签名,打包,第三方依赖进行处理,具体详情可以看我的范例代码,如下所示:

//代表该项目是一个android项目
apply plugin: 'com.android.application'
//greendao的相关配置
apply plugin: 'org.greenrobot.greendao'
//butterknife相关配置
apply plugin: 'com.jakewharton.butterknife'

//获取当前时间
static def getCurrentTime() {
    return new Date().format("yyyyMMdd", TimeZone.getTimeZone("UTC"))
}

//自定义安全签名信息
def keystoreFilepath = ''
def keystorePSW = ''
def keystoreAlias = ''
def keystoreAliasPSW = ''
//默认的签名文件
def keyFile = file('s.keystore.temp')
//根据我们在local.properties下的配置参数keystore.password等获取签名文件的配置信息。
Properties localProperties = new Properties()
//加载根文件夹下的本地属性文件
localProperties.load(project.rootProject.file('local.properties').newDataInputStream())
//获取签名文件的路径
keystoreFilepath = localProperties.getProperty("keystore.path")

//通过签名文件的路径获取签名文件的信息
if (keystoreFilepath) {
    keyFile = file(keystoreFilepath)
    keystorePSW = localProperties.getProperty("keystore.password")
    keystoreAlias = localProperties.getProperty("keystore.alias")
    keystoreAliasPSW = localProperties.getProperty("keystore.alias_password")
}

//获取gradleProperties文件中定义的versionName,versionCode属性
Properties gradleProperties = new Properties()
gradleProperties.load(project.rootProject.file('gradle.properties').newDataInputStream())
String configVersionName = gradleProperties.getProperty("versionName")
int configVersionCode = Integer.parseInt(gradleProperties.getProperty("versionCode"))

android {
    compileSdkVersion rootProject.ext.compileSdkVersion

    //解决android方法数超过限制问题
    dexOptions {
        jumboMode = true
    }

    //解决android打包so文件
    sourceSets {
        main {
            jniLibs.srcDir 'libs'
        }
    }

    //签名信息配置
    signingConfigs {
        release {
            try {
                storeFile keyFile
                storePassword keystorePSW
                keyAlias keystoreAlias
                keyPassword keystoreAliasPSW
            } catch (ex) {
                throw new InvalidUserDataException(ex.toString())
            }
        }
        pre {
            storeFile file('D:/Users/.android/debug.keystore')
        }
    }

    //默认配置
    defaultConfig {
        applicationId "com.example.administrator.freestyle"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode configVersionCode
        versionName configVersionName
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        //兼容android5.0之前对vectorDrawables的支持
        vectorDrawables.useSupportLibrary = true
        //默认情况下,Android应用程序具有SingleDex支持,它将您的应用程序限制为只有65536个方法(引用)
        // 所以multidexEnabled = true就意味着现在你可以在你的应用程序中编写超过65536个方法(引用)
        multiDexEnabled = true
    }

    buildTypes {
        release {
            minifyEnabled false
            debuggable false
            minifyEnabled true //启用Proguard,会对代码进行混淆和压缩
            shrinkResources true //是否清理无用资源,依赖于minifyEnabled
            zipAlignEnabled true //是否启用zipAlign压缩
            signingConfig signingConfigs.release
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }

        debug {
            debuggable true
            minifyEnabled false  //不启用Proguard
            shrinkResources false //是否清理无用资源,依赖于minifyEnabled
            zipAlignEnabled false //是否启用zipAlign压缩
            signingConfig signingConfigs.debug
            //定义res资源文件里的值
            resValue "string", "app_name", "freeStyle"

            // 动态修改常量字段
            buildConfigField("String", "WECHAT_APPID", "\"\"")
            buildConfigField("String", "QQ_APPID", "\"\"")
            buildConfigField("String", "BASE_URL", "\"\"")

            // 修改 AndroidManifest.xml 里渠道变量
            manifestPlaceholders = [
                    BD_MAP_APPKEY: "",
                    TENCENT_APPID: "",
                    JPUSH_PKGNAME: "",
                    JPUSH_APPKEY : "",
                    JPUSH_CHANNEL: "developer-debug"
            ]

            //定义手机的架构类型
            ndk {
                abiFilters 'x86', 'x86_64', 'armeabi'
            }
        }
    }

    //apk文件重命名
    android.applicationVariants.all { variant ->
        variant.outputs.all {
            def buildType = variant.buildType.name
            outputFileName = "freeStyle-v${defaultConfig.versionName}-${buildType}-${defaultConfig.versionCode}-${getCurrentTime()}.apk"
        }

    }

    //添加依赖
    dependencies {
        implementation fileTree(include: ['*.jar'], dir: 'libs')
         implementation "com.android.support:appcompat-v7:$rootProject.ext.supportLibVersion"
        implementation "com.android.support:design:$rootProject.ext.supportLibVersion"
        implementation 'com.android.support.constraint:constraint-layout:1.0.2'
        implementation "com.android.support:multidex:$rootProject.ext.multidexVersion"
        testImplementation 'junit:junit:4.12'
        androidTestImplementation 'com.android.support.test:runner:1.0.1'
        androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
        implementation "com.jakewharton:butterknife:$rootProject.ext.butterknifeVersion"
        annotationProcessor "com.jakewharton:butterknife-compiler:$rootProject.ext.butterknifeVersion"
        implementation "com.github.bumptech.glide:glide:$rootProject.ext.glideVersion"
        annotationProcessor "com.github.bumptech.glide:compiler:$rootProject.ext.glideVersion"
        implementation "com.github.bumptech.glide:okhttp3-integration:$rootProject.ext.glideVersion"
        implementation "io.reactivex.rxjava2:rxjava:$rootProject.ext.rxjava2Version"
        implementation "io.reactivex.rxjava2:rxandroid:$rootProject.ext.rxandroidVersion"
        implementation 'com.trello.rxlifecycle2:rxlifecycle:2.2.1'
        implementation 'com.trello.rxlifecycle2:rxlifecycle-components:2.2.1'
        implementation "com.squareup.retrofit2:retrofit:$rootProject.ext.retrofit2Version"
        implementation "com.squareup.retrofit2:converter-gson:$rootProject.ext.retrofit2Version"
        implementation "com.squareup.retrofit2:adapter-rxjava2:$rootProject.ext.retrofit2Version"
        implementation "com.squareup.okhttp3:okhttp:$rootProject.ext.okhttpVersion"
        implementation "com.squareup.okhttp3:logging-interceptor:$rootProject.ext.okhttpVersion"
        implementation "org.greenrobot:greendao:$rootProject.ext.greendaoVersion"
        implementation "org.greenrobot:eventbus:$rootProject.ext.eventbusVersion"
        implementation "com.orhanobut:logger:$rootProject.ext.loggerVersion"
        implementation 'com.qiniu:qiniu-android-sdk:7.3+'
        implementation 'com.tencent.mm.opensdk:wechat-sdk-android-with-mta:+'
        implementation 'com.afollestad.material-dialogs:core:0.9.6.0'
        implementation 'com.github.chrisbanes:PhotoView:2.1.3'
        implementation 'com.github.CymChad:BaseRecyclerViewAdapterHelper:2.9.34'
        implementation 'pl.droidsonroids.gif:android-gif-drawable:1.2.10'
        implementation 'de.hdodenhof:circleimageview:2.1.0'
       }
}

setting.gradle

setting.gradle的作用主要就是引用子module,默认状态下只有一个app module,如下所示:

include ':app'

总结

Gradle 是 Android 现在主流的编译工具,虽然在Gradle 出现之前和之后都有对应更快的编译工具出现,但是 Gradle 的优势就在于它是亲儿子,Gradle 确实比较慢,这和它的编译过程有关,但是现在的Gradle 编译速度已经有了成倍提高。除此之外,相对其他编译工具,最重要的,他和 Android Studio 的关系非常紧密,可以说对于一些简单的程序我们几乎不需要任何代码上的配置只使用 Android Studio 就可以完成编译和运行

猜你喜欢

转载自blog.csdn.net/lijizhi19950123/article/details/79343517
今日推荐