build.gradle
apply plugin: 'com.android.application' android { compileSdkVersion rootProject.ext.android.compileSdkVersion //编译sdk版本 buildToolsVersion rootProject.ext.android.buildToolsVersion //编译tools version defaultConfig { applicationId "com.example.myapp" minSdkVersion rootProject.ext.android.minSdkVersion //最低sdk targetSdkVersion rootProject.ext.android.targetSdkVersion//目标sdk versionCode 6 versionName "1.0" multiDexEnabled true //使用multidex // testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } signingConfigs { //签名配置 release { keyAlias 'deviceapp' keyPassword '111111' storeFile file('../deviceAppKey.key') storePassword '111111' } debug { //empty } } buildTypes { debug { versionNameSuffix "-debug" minifyEnabled false zipAlignEnabled false shrinkResources false signingConfig signingConfigs.debug } release { //混淆 minifyEnabled true //Zipalign优化 zipAlignEnabled true // 移除无用的resource文件 minifyEnabled true有效 shrinkResources true signingConfig signingConfigs.release proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'//混淆配置 } } dataBinding {//data binding 使用 enabled = true } } dependencies { compile fileTree(include: ['*.jar'], dir: 'libs')//文件夹下面全部依赖 compile files('libs/gson.jar')//单文件依赖 // androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { // exclude group: 'com.android.support', module: 'support-annotations' // }) compile 'com.android.support.constraint:constraint-layout:1.0.2' compile rootProject.ext.libSupportAppcompatV7 compile rootProject.ext.libGson
compile rootProject.ext.libOKHttp
// compile rootProject.ext.libOKIO
compile rootProject.ext.libRetorfit
// compile rootProject.ext.libOKHttpLogging
compile rootProject.ext.libRetorfitConvertGson
compile rootProject.ext.libRXJava
compile rootProject.ext.libRXAndroid
compile rootProject.ext.libRXRetrofitAdapter
compile project(':configlibrary')//module library依赖 compile (project(':configlibrary')) { exclude group: "com.android.support" }//类库去重处理 }
这里涉及到统一版本号(类库版本,编译版本,使用版本)管理,为了防止相同项目引入相同类库不同版本,以及编译相关版本,方便后续统一维护修改,所以需要统一版本号
在项目根目录创建config.gradle将通用的类库写在里面,内容如下
ext { android = [ compileSdkVersion: 25, buildToolsVersion: "25", minSdkVersion : 18, targetSdkVersion : 25 ] def supportVersion = "23.4.0" def gsonVersion = "2.7" def butterKnifeVersion = "8.4.0" def butterKnifeCompilerVersion = "8.4.0" def okHttpVersion = "3.6.0"; def okIOVersion = "1.11.0"; def retrofitVersion = "2.2.0"; def okHttpLogVersion = "3.6.0"; def rxJavaVersion = "2.0.7" def rxAndroidVersion = "2.0.1" def retorfitRxAdapterVersion = "2.2.0" libSupportAppcompatV7 = "com.android.support:appcompat-v7:${supportVersion}" libSupportDesign = "com.android.support:design:${supportVersion}" libSupportRecyclerview = "com.android.support:recyclerview-v7:${supportVersion}" libSupportV4 = "com.android.support:support-v4:${supportVersion}" libGson = "com.google.code.gson:gson:${gsonVersion}" libButterKnife = "com.jakewharton:butterknife:${butterKnifeVersion}" libButterKnifeCompiler = "com.jakewharton:butterknife-compiler:${butterKnifeCompilerVersion}" libOKHttp = "com.squareup.okhttp3:okhttp:${okHttpVersion}" libOKIO = "com.squareup.okio:okio:${okIOVersion}" libRetorfit = "com.squareup.retrofit2:retrofit:${retrofitVersion}" libRetorfitConvertGson = "com.squareup.retrofit2:converter-gson:${retrofitVersion}" libOKHttpLogging = "com.squareup.okhttp3:logging-interceptor:${okHttpLogVersion}" libRXJava = "io.reactivex.rxjava2:rxjava:${rxJavaVersion}" libRXAndroid = "io.reactivex.rxjava2:rxandroid:${rxAndroidVersion}" libRXRetrofitAdapter = "com.squareup.retrofit2:adapter-rxjava2:${retorfitRxAdapterVersion}" }
在根目录build.gradle里引用该配置文件
// Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.3.1' } } apply from: "config.gradle"
即可在其它module内使用,统一通用版本,防止相同类库产生多个版本
编译产生java.lang.OutOfMemoryError: GC overhead limit exceeded问题解决
// solve java.lang.OutOfMemoryError: GC overhead limit exceeded dexOptions { preDexLibraries true javaMaxHeapSize "3g" incremental true dexInProcess = true }
debug,release打包签名配置
signingConfigs { config { keyAlias 'key0' keyPassword 'xinju123' storeFile file('F:/StudioProjects/PublisherSystem/xinju_mediaplayer.jks') storePassword 'xinju123' } } buildTypes { debug { versionNameSuffix "-debug" applicationIdSuffix ".alpha" minifyEnabled false zipAlignEnabled false shrinkResources false // signingConfig signingConfigs.config } release { versionNameSuffix "-release" applicationIdSuffix ".beata" debuggable false jniDebuggable false //混淆 minifyEnabled false //Zipalign优化 zipAlignEnabled false // 移除无用的resource文件 minifyEnabled true有效 shrinkResources false signingConfig signingConfigs.config // proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'//混淆配置 } }
项目内部分为多个功能模块,同时会产生在同一个res资源内的layout,value,drawable对应文件有很多,不方便查找及后续的分离处理,
因此需要对资源内容进行按功能模块进行分离除处理,使用gradle可以轻松实现此需求
在module工程内的build.gradle android内加入sourceSets命令
android { compileSdkVersion rootProject.ext.android.compileSdkVersion buildToolsVersion rootProject.ext.android.buildToolsVersion defaultConfig { minSdkVersion rootProject.ext.android.minSdkVersion //最低sdk targetSdkVersion rootProject.ext.android.targetSdkVersion//目标sdk versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } sourceSets { //资源分割模块化处理 main.res.srcDirs += 'src/main/res-logcat' main.res.srcDirs += 'src/main/res-config' main.res.srcDirs += 'src/main/res-config2' main.res.srcDirs += 'src/main/res-httpchunk' main.res.srcDirs += 'src/main/res-logviewer' main.res.srcDirs += 'src/main/res-standout' } }
最终效果
可以看到,多个res资源目录按功能分割好了。
或者按目录进行划分处理
sourceSets { //资源分割模块化处理 // java.srcDirs('src/test1','src/test2') main.java.srcDirs('src/test1/java')//定义java源文件目录 main.res.srcDirs('src/test1/res')//定义资源目录,drawable layout values }
gradle 生产同一程序,不同packgeName方法
http://blog.csdn.net/chenaini119/article/details/46874241
productFlavors{ flavors_release{ manifestPlaceholders = [str:"releaseStr",package_name:"com.example.android.newsreader"] applicationId "com.example.android.newsreader" } flavors_dev{ manifestPlaceholders = [str:"devStr",package_name:"com.example.android.newsreaderdev"] applicationId "com.example.android.newsreaderdev" } }
androidStudio3.0 gradle flavor打包
buildTypes { ...... flavorDimensions "ver_test","ver_online" productFlavors { opt_test { dimension "ver_test" applicationIdSuffix ".test" } opt_online { dimension "ver_online" applicationIdSuffix ".online" } } //包数量flavorDimensions * productFlavors (2x2) }
在Android Studio的右侧的gradle面板中点击 按钮刷新下,于是在build子栏目中
其中以assemble*打头的都是生成apk的选项,生成的apk在build/outputs/apk中,这里我们对任一项双击即可生成对应的apk
对应flavors_release和flavors_dev的apk应该就是和这两个,于是分别双击他们等待各自生成apk的过程
工程内部代码功能分离
sourceSets { main { def dirs = ['p_widget', 'p_theme', 'p_location', 'p_log','p_im','p_share'] dirs.each { dir -> java.srcDir("src/$dir/java") res.srcDir("src/$dir/res") } } wm { dirs.each { dir -> java.srcDir("src/${dir}/wm/java") res.srcDir("src/${dir}/wm/res") } } mt { dirs.each { dir -> java.srcDir("src/${dir}/mt/java") res.srcDir("src/${dir}/mt/res") } } }
gradle动态控制BuildConfig.java
BuildConfig.java是Android Gradle自动生成的一个java类文件,无法手动编译,但是可以通过Gradle控制,也就是说它是动态可配置的
buildTypes { debug { //debug包BuildConfig LOG_DEBUG 为true buildConfigField "boolean", "LOG_DEBUG", "true" buildConfigField "String", "Flag", "111" } release { //release包BuildConfig LOG_DEBUG 为false buildConfigField "boolean", "LOG_DEBUG", "false" //release的包中BuildConfig.Flag 就会被赋值为 222 buildConfigField "String", "Flag", "222" } }
在配置加入如上命令时,编译后 BuildConfig会生成LOG_DEBUG,Flag常量,并且会根据不同的包产生不同值
同时也可以生成resValue内容,如,生成strings.xml类型的字符串的值,
buildTypes { debug { resValue "string", "app_name1", "MyApp_debug" ... } release { //将release的包中名为 app_name 的 string value 值改为 app1 resValue "string", "app_name1", "MyApp_release" } }
值得注意,resValue生成内容并不是在strings.xml内,而在MyAppappuildgenerated es esValuesdebugvaluesgenerated.xml内,内容如下
<?xml version="1.0" encoding="utf-8"?> <resources> <!-- Automatically generated file. DO NOT MODIFY --> <!-- Values from build type: debug --> <string name="app_name1" translatable="false">MyApp_debug</string> </resources>
关于gradle编译命令:
命令行切换到项目根目录:
执行gradlew -v如有内容输出即可证明正常
基本命令:
./gradlew -v 版本号
./gradlew clean 清除Project目录下的build文件夹
./gradlew build 检查依赖并编译打包
注意gradlew build 命令把debug、release环境的包都打出来
./gradlew assembleDebug 编译并打Debug包
./gradlew assembleRelease 编译并打Release的包
./gradlew installRelease Release模式打包并安装
./gradlew uninstallRelease 卸载Release模式包
gradlew app:clean 清理app module输出文件
gradlew app:build 构建app module
gradlew app:check lint检查
gradlew app:assembleRelease 打release安装包
gradlew app:assembleDebug debug安装包
依赖类库:
对只依赖类库中的很小功能的,需要对内容进行精简处理重新打包
例如:butterknife
compile('com.jakewharton:butterknife:8.4.0') {
exclude group: 'com.android.support', module: 'support-annotations'
}
annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'
其它module
// 编译CommonSDK模块,但是去掉此模块中对com.android.support的依赖,防止重复依赖报错
compile (project(':CommonSDK')) { exclude group: "com.android.support" }
依赖 aar 包
把 aar 包放到 libs 目录下
repositories {
flatDir {
dirs 'libs'
}
}
implementation(name:'faceplatform-release', ext:'aar')
aar 包需要被多个 module 依赖时,我们就不能把 aar 包放在单一的 module 中,我们可以在项目的根目录创建一个目录,比如叫 aar 目录,然后把我们的 aar 包放进去
在项目的根目录的 build.gradle 的 allprojects 标签下的 repositories 添加
flatDir {
dirs ../aar // ../aar 表示根目录下的 aar 文件夹。
}
然后就可以添加依赖了 compile(name:'tt',ext:'aar')
compile是默认的那个,其含义是包含所有的依赖包,即在APK
provided的意思是提供编译支持,但是不会写入apk
debugCompile/releaseCompile
更多介绍:https://mp.weixin.qq.com/s/hCXLz-9BnAOGWyZ2eRikKg
两个重要的命令:
Gradle查看Android项目中库的依赖关系
使用gradlew <projectname>:dependencies --configuration compile检测依赖关系,去除重复
dependencies指令,
./gradlew :app:dependencies --configuration compile
dependencyInsight指令,查看指定库的依赖关系
./gradlew :app:dependencyInsight --dependency fastjson --configuration compile
studio3.0 compile 替换为 implementation 引用类库,查找改为,
dependencies指令,
gradlew :app:dependencies --configuration releaseCompileClasspath
:app:dependencies
dependencyInsight指令
gradlew :app:dependencyInsight --dependency support-annotations --configuration releaseCompileClasspath
:app:dependencyInsight
studio3.0
implementation 替换compile依赖类库,只对本module有效,不能传递依赖,(隔离功能)
api可以对外暴露依赖类库,可传递