Android开发经验谈Android技术知识Android开发

android有关gradle配置

2017-12-14  本文已影响119人  ccccccal
gradle使用source set 的概念,一个source set就是一系列资源文件,其将会被便衣和执行,对于android项目,main就是一个source set,其包含了所有的资源文件,相对main测试文件test也是一个source set,只做测试

基础命令:

打包需要在build配置签名文件以及密码

 signingConfigs {
        debug {
            // No debug config
        }

        release {
            storeFile file("../yourapp.keystore")
            storePassword "your password"
            keyAlias "your alias"
            keyPassword "your password"
        }
    }

gradlew配置文件结构和eclipse结构相同

android {
     sourceSets {
       main {
         manifest.srcFile 'AndroidManifest.xml'
         java.srcDirs = ['src']
         resources.srcDirs = ['src']
         aidl.srcDirs = ['src']
         renderscript.srcDirs = ['src']
         res.srcDirs = ['res']
         assets.srcDirs = ['assets']
    }
     androidTest.setRoot('tests')
    } 
}

在grade文件中配置,将会保存eclipse目录结构,如果有依赖的jar包,需要告诉gradle,假设jar包会在一个叫做libs的文件夹内,那么你应该这么配置(现在这条会默认配置):

dependencies {
       compile fileTree(dir: 'libs', include: ['*.jar'])
}

gradle 配置解析:

创建一个新的android项目时,会默认生成三个gradle文件

根目录的gradle文件一般如下

//声明自定义的gradle文件
apply from: "config.gradle"
buildscript {
    repositories {//配置仓库,使用jcenter,现在studio3.0以后默认使用google
        jcenter()
        google()
    }
    dependencies {//配置gradle的插件默认配置gradle,我这里还配置tinker插件,用于热更新
        classpath 'com.android.tools.build:gradle:3.0.1'
        classpath 'com.tencent.bugly:tinker-support:1.1.1'
        }
}

allprojects {//定义模块默认属性
    repositories {
        jcenter()
        google()
    }
}

task clean(type: Delete) {//我这里配置task clean的时候直接删除项目的build文件夹
    delete rootProject.buildDir
}

模块内build.gradle文件

以下是studio3.0之前的配置,3.0之后稍后改动

//声明模块要使用的插件,默认配置android.application
apply plugin: 'com.android.application'
   android {
       compileSdkVersion 22//配置编译app的api版本
       buildToolsVersion "22.0.1"//3.0之后已经去除,不需要再配置
       defaultConfig {
           applicationId "com.gradleforandroid.gettingstarted"//默认对应清单文件里的包名
           minSdkVersion 14//兼容的最小版本号
           targetSdkVersion 22//最适合的版本号
           versionCode 1//版本号标识
           versionName "1.0"//版本名字,一般用于给用户展示,除此没有其他用处
       }
       buildTypes {
           release {
               minifyEnabled false
               proguardFiles getDefaultProguardFile
                ('proguard-android.txt'), 'proguard-rules.pro'
           }
        } 
    }
    dependencies {//3.0以后使用implementation  来代替compile
       compile fileTree(dir: 'libs', include: ['*.jar'])
       compile 'com.android.support:appcompat-v7:22.2.0'
       implementation  'com.android.support:appcompat-v7:22.2.0'

     }

使用BuildConfig和resources动态配置不同渠道资源

比如baseUrl

  release {
            //关闭日志输出
            buildConfigField("boolean", "LOG_DEBUG", "false")
            //配置默认baseUrl
            buildConfigField("String", "SERVER_URL", rootProject.ext.configs['releaseUrl'])
            //配置下载地址
            buildConfigField("String", "DOWNLOAD_URL", rootProject.ext.download['releaseUrl'])
            // 移除无用的resource文件
            shrinkResources true
            //是否混淆
            minifyEnabled true
            //混淆文件(.text处于SDK下面,针对全项目,.pro只针对本项目)
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            //配置签名文件
            signingConfig signingConfigs.sweetorange_sign
        }

比如app名字:

android {
       buildTypes {
           debug {
               resValue "string", "app_name", "我的测试版本"
           }
           release {
               resValue "string", "app_name", "我是正式版本"
            } 
       }
}

配置全局配置

关于多moudle开发,方便多人分模块开发,这也是组件化开发的模式,这样每个moudle都会配置各自的build.gradle文件,为了配置统一,一般配置全局配置,让各个moudle去调用

全局配置有两种方法

两种方式一样,个人觉得第二种更方便管理

有关第二种:

主要是配置了项目所使用到的第三方依赖库,有关依赖哭的混淆可以看我的混淆配置https://www.jianshu.com/p/181d6f2d5bae

ext {

    configs = [//配置baseUrl
            debugUrl  : '"http://111.111.1.111.8080"',
            releaseUrl: '"https://www.baidu.com"',
    ]

       android = [compileSdkVersion        : 25,
               applicationId            : "com.sweetorange.read",
               minSdkVersion            : 16,
               targetSdkVersion         : 25,
               versionCode              : 13,
               versionName              : "1.3",
               testInstrumentationRunner: "android.support.test.runner.AndroidJUnitRunner"]

    dependencies = [//配置所有的第三方依赖库(不多不多,也就二十个)

            //multidex方法书超过64K
            "multidex"                     : 'com.android.support:multidex:1.0.1',

            //bumptech,用于glide配置okhttp请求
            "bumptech"                     : 'com.github.bumptech.glide:okhttp3-integration:1.4.0@aar',

            //pgyer蒲公英用于测试
            "pgyer"                        : 'com.pgyersdk:sdk:2.8.1',

            //MZBannerView,banner轮播图,用于引导页面
            "MZBannerView"                 : 'com.github.pinguo-zhouwei:MZBannerView:v2.0.0',

            //bugly ,热修复
            "bugly"                        : 'com.tencent.bugly:crashreport_upgrade:1.3.4',

            //微信
            "wechat"                       : 'com.tencent.mm.opensdk:wechat-sdk-android-with-mta:1.0.2',

            //伸缩textView
            "expandableTextView"           : 'com.ms-square:expandableTextView:0.1.4',

            //屏幕适配
            "autolayout"                   : 'com.zhy:autolayout:1.4.5',

            //v7包
            "support_v7"                   : 'com.android.support:appcompat-v7:25.3.1',

            //设置阅读页动画
            "nineoldandroids"              : 'com.nineoldandroids:library:2.4.0',

            //Xutils3用于网络请求
            "xutils"                       : 'org.xutils:xutils:3.3.40',

            //design包
            "support_design"               : 'com.android.support:design:25.3.0',

            //glide
            "glide"                        : 'com.github.bumptech.glide:glide:3.7.0',

            //v4
            "support_v4"                   : 'com.android.support:support-v4:25.3.0',

            //drawable
            "support_drawable"             : 'com.android.support:support-vector-drawable:25.1.0',

            //eventbus
            "eventbus"                     : 'org.greenrobot:eventbus:3.0.0',

            //fastJson
            "fastjson"                     : 'com.alibaba:fastjson:1.2.23',

            //litepal
            "litepal"                      : 'org.litepal.android:core:1.5.1',

            //circleimageview
            "circleimageview"              : 'de.hdodenhof:circleimageview:2.1.0',

            //klog
            "klog"                         : 'com.github.zhaokaiqiang.klog:library:1.5.0',

            //Luban
            "Luban"                        : 'top.zibin:Luban:1.1.3',

            //jsoup
            "jsoup"                        : 'org.jsoup:jsoup:1.10.2',

            //permission
            "permission"                   : 'com.yanzhenjie:permission:1.0.7',

            //album
            "album"                        : 'com.yanzhenjie:album:1.0.7',

            //constraint-layout
            "constraint_layout"            : 'com.android.support.constraint:constraint-layout:1.0.0-alpha8',

            //BaseRecyclerViewAdapterHelper
            "BaseRecyclerViewAdapterHelper": 'com.github.CymChad:BaseRecyclerViewAdapterHelper:2.9.18',

            //badgeview
            "badgeview"                    : 'q.rorbin:badgeview:1.1.2',

            //butterknife
            "butterknife"                  : 'com.jakewharton:butterknife:8.7.0',

            //butterknife
            "butterknife_two"              : 'com.jakewharton:butterknife-compiler:8.7.0',

            //lombok
            "lombok"                       : 'org.projectlombok:lombok:1.16.18',

            //nohttp
            "nohttp"                       : 'com.yanzhenjie.nohttp:nohttp:1.1.4',

            //junit
            "junit"                        : 'junit:junit:4.12',

            //okhttp
            "okhttp"                       : 'com.yanzhenjie.nohttp:okhttp:1.1.4',

            //添加注解,配合lombok
            "annotation"                   : 'org.glassfish:javax.annotation:10.0-b28',

            "SmartRefreshLayout"           : 'com.scwang.smartrefresh:SmartRefreshLayout:1.0.3',
            "SmartRefreshHeader"           : 'com.scwang.smartrefresh:SmartRefreshHeader:1.0.3',
    ]
}

使用全局配置

主项目build文件声明自定义的build文件

apply from: "config.gradle"

在moudle中使用

apply plugin: 'com.android.application'

// 依赖插件脚本
apply from: 'tinker-support.gradle'

android {

    //项目编译版本
    compileSdkVersion rootProject.ext.android.compileSdkVersion
    defaultConfig {
        //项目包名
        applicationId rootProject.ext.android.applicationId
        //最低兼容
        minSdkVersion rootProject.ext.android.minSdkVersion
        //最佳使用版本
        targetSdkVersion rootProject.ext.android.targetSdkVersion
        //版本号
        versionCode rootProject.ext.android.versionCode
        //版本名
        versionName rootProject.ext.android.versionName
        testInstrumentationRunner rootProject.ext.android.testInstrumentationRunner
        vectorDrawables.useSupportLibrary = true
        multiDexEnabled true
        flavorDimensions "versionCode"
    }
    buildTypes {
        release {
            //关闭日志输出
            buildConfigField("boolean", "LOG_DEBUG", "false")
            //配置默认baseUrl
            buildConfigField("String", "SERVER_URL", rootProject.ext.configs['releaseUrl'])
            //配置下载地址
            buildConfigField("String", "DOWNLOAD_URL", rootProject.ext.download['releaseUrl'])
            // 移除无用的resource文件
            shrinkResources true
            //是否混淆
            minifyEnabled true
            //混淆文件(.text处于SDK下面,针对全项目,.pro只针对本项目)
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
           }

        debug {
            buildConfigField("String", "SERVER_URL", rootProject.ext.configs['debugUrl'])
            minifyEnabled true
            //混淆文件(.text处于SDK下面,针对全项目,.pro只针对本项目)
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            buildConfigField("boolean", "LOG_DEBUG", "true")
            //配置下载地址
            buildConfigField("String", "DOWNLOAD_URL", rootProject.ext.download['debugUrl'])
            }
    }

    //配置多渠道包
    productFlavors {
        huawei {}
        xiaomi {}
        qh360 {}
        baidu {}
    }

     //使用友盟多渠道打包替换
    productFlavors.all {
        flavor -> flavor.manifestPlaceholders = [UMENG_CHANNEL_VALUE: name]
    }

    //layout文件分包
    sourceSets {
        main {
            res.srcDirs =
                    [
                            'src/main/res/layouts/activities',
                            'src/main/res/layouts/dialogs',
                            'src/main/res/layouts/fragments',
                            'src/main/res/layouts/headviews',
                            'src/main/res/layouts/items',
                            'src/main/res/layouts/views',
                            'src/main/res/layouts',
                            'src/main/res'
                    ]
        }
    }

    //配置使用lambda表达式
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

//配置仓库,可以使用全局配置,默认jcenter,3.0以后默认google
allprojects {
    repositories {
        jcenter()
        maven { url "https://jitpack.io" }
        maven { url "https://raw.githubusercontent.com/Pgyer/mvn_repo_pgyer/master" }

    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    implementation files('libs/alipaySdk-20170309.jar')
    implementation project(':sharelibrary')
    implementation project(':UpdateAppUtils')
    implementation rootProject.ext.dependencies.pgyer
    implementation rootProject.ext.dependencies.bumptech
    implementation rootProject.ext.dependencies.wechat
    implementation rootProject.ext.dependencies.MZBannerView
    implementation rootProject.ext.dependencies.expandableTextView
    implementation rootProject.ext.dependencies.autolayout
    implementation rootProject.ext.dependencies.support_v7
    implementation rootProject.ext.dependencies.nineoldandroids
    implementation rootProject.ext.dependencies.xutils
    implementation rootProject.ext.dependencies.support_design
    implementation rootProject.ext.dependencies.glide
    implementation rootProject.ext.dependencies.support_v4
    implementation rootProject.ext.dependencies.support_drawable
    implementation rootProject.ext.dependencies.eventbus
    implementation rootProject.ext.dependencies.fastjson
    implementation rootProject.ext.dependencies.litepal
    implementation rootProject.ext.dependencies.circleimageview
    implementation rootProject.ext.dependencies.klog
    implementation rootProject.ext.dependencies.Luban
    implementation rootProject.ext.dependencies.jsoup
    implementation rootProject.ext.dependencies.permission
    implementation rootProject.ext.dependencies.album
    implementation rootProject.ext.dependencies.constraint_layout
    implementation rootProject.ext.dependencies.BaseRecyclerViewAdapterHelper
    implementation rootProject.ext.dependencies.badgeview
    implementation rootProject.ext.dependencies.butterknife
    annotationProcessor rootProject.ext.dependencies.butterknife_two
    implementation rootProject.ext.dependencies.lombok
    annotationProcessor rootProject.ext.dependencies.lombok
    implementation rootProject.ext.dependencies.nohttp
    implementation rootProject.ext.dependencies.okhttp
    testImplementation rootProject.ext.dependencies.junit
    provided rootProject.ext.dependencies.annotation
    implementation rootProject.ext.dependencies.SmartRefreshLayout
    implementation rootProject.ext.dependencies.SmartRefreshHeader
    implementation rootProject.ext.dependencies.bugly
    implementation rootProject.ext.dependencies.multidex
    implementation project(':PushSDK')
    implementation files('libs/umeng-analytics-7.4.0.jar')
    implementation files('libs/umeng-common-1.4.0.jar')
}

gradle的以依赖管理

gradle支持三种仓库

一个依赖需要三个元素:

例如:

implementation 'com.github.ALguojian:SpannableHelper:1.0'

gradle使用groovy编写,完整表述如下:

implementation group: 'com.github.ALguojian' , name: 'SpannableHelper' , version: '1.0'

有关公司私人权限仓库配置:

repositories {
       maven {
           url "http://repo.acmecorp.com/maven2"
           credentials {
               username 'user'
               password 'secretpassword'
           }
        } 
   

建议有关密码都配置在gradle.properties文件中,并添加到忽略文件

# 应用版本名称
VERSION_NAME=1.0.0
# 应用版本号
VERSION_CODE=100

使用如下:

android {
    compileSdkVersion project.ANDROID_BUILD_SDK_VERSION as int
    buildToolsVersion project.ANDROID_BUILD_TOOLS_VERSION
 
    defaultConfig {
        versionCode project.VERSION_CODE as int
        versionName project.VERSION_NAME
        minSdkVersion project.ANDROID_BUILD_MIN_SDK_VERSION as int
        targetSdkVersion project.ANDROID_BUILD_TARGET_SDK_VERSION as int
    }
}

添加so包如下:

用c或者c++写的library叫做so包,android插件默认是支持的,需要把so文件放在对应文件夹中

app
   ├── AndroidManifest.xml
   └── jniLibs
       ├── armeabi
       │   └── nativelib.so
       ├── armeabi-v7a
       │   └── nativelib.so
       ├── mips
       │   └── nativelib.so
       └── x86
           └── nativelib.so

被依赖的moudle编译之后会生成aar文件,使用aar文件和jar相同

关于以来的配置:

关于配置多版本

buildTypes下面配置多渠道配置:

android {
    buildTypes {
        alguojain{
            applicationIdSuffix ".alguojain"
            versionNameSuffix "-alguojain"
            buildConfigField "String","API_URL","\"http://alguojain.com"\"
         }
    }
}

关于配制多渠道 product flavors

android {

    flavorDimensions "123", "456"
    productFlavors {
        aaa{
             applicationId 'com.alguojian.aaa'
              flavorDimension "123"
             versionCode 3
        }
        bbb{
             flavorDimension "456"
             applicationId 'com.alguojian.bbb'
             minSdkVersion 14
             versionCode 4
        }
    }
}

配置渠道过滤器

android.variantFilter { variant ->
       if(variant.buildType.name.equals('release')) {
           variant.getFlavors().each() { flavor ->
               if (flavor.name.equals(tbl)) { variant.setIgnore(true);
            }
        }
    }
}

配置多版本的签名文件

有关签名,debug版本shistudio默认的签名,使用的是公共的签名文件,下面alguojian版本使用initWith方法是使用debug版本的配置

android {
       signingConfigs {

           alguojian.initWith(signingConfigs.debug)

           release {
               storeFile file("release.keystore")
               storePassword"secretpassword"
               keyAlias "gradleforandroid"
               keyPassword "secretpassword"
           }
      }
}

针对不同版本不同渠道配置不同签名

android {
       buildTypes {
           release {
               productFlavors.red.signingConfig signingConfigs.aaa
               productFlavors.blue.signingConfig signingConfigs.bbb
           }
       }
}

多moudle开启多线程构建(电脑内存要大,要大,要大!!!)

需要在grade.properties文件中配置如下属性:


org.gradle.parallel=true

自定义gradle插件,待定,正在学习grovvy

上一篇下一篇

猜你喜欢

热点阅读