Android中build.gradle的實用技巧
1.替換符的使用
(1)在app-android-defaultConfig (或者多渠道打包)下面可以這樣使用
android { defaultConfig { manifestPlaceholders = [ //高德地圖key GDKEY: "123456789", ] } }
(2)在AndroidManifest.xml 檔案的application 標籤下面這樣引用
<!-- 高德地圖 --> <meta-data android:name="com.amap.api.v2.apikey" android:value="${GDKEY}" />
2.打包設定appname(啟動圖示類似,res下面的都可以這樣使用)
android { defaultConfig { //在string.xml中不能出現app_name這個欄位,否則生成報錯 resValue "string", "app_name", "app名稱" } }
3.生成BuildConfig.java欄位
在build.gradle中
android { defaultConfig { //生成一個boolea型別的變數 buildConfigField "boolean", "IS_TEST_URL", "true" //生成一個字串變數 buildConfigField "String", "APP_UPDATE_TIME", "\"${System.currentTimeMillis().toString()}\"" } }
在java程式碼
public final class BuildConfig { // Fields from product flavor: 渠道名 public static final String APP_UPDATE_TIME = "1551754973086"; public static final boolean IS_TEST_URL = false; }
4.多渠道打包(注意在defaultConfig下面新增flavorDimensions "versionCode")
android { compileSdkVersion 28 defaultConfig { minSdkVersion 19 targetSdkVersion 28 testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" flavorDimensions "versionCode" productFlavors { name1 { applicationId "com.test.name" versionName "0.1.4" versionCode 5 resValue "string", "app_name", "app名字" buildConfigField "boolean", "IS_TEST_URL", "false" buildConfigField "String", "APP_UPDATE_TIME", "\"${System.currentTimeMillis().toString()}\"" } }
5.設定簽名
android{ signingConfigs { release { keyAlias '' keyPassword '' storeFile file('./sign.jks') storePassword '' v2SigningEnabled false } } buildTypes { release { debuggable false minifyEnabled true shrinkResources true useProguard true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' signingConfig signingConfigs.release } debug { debuggable true minifyEnabled false shrinkResources false useProguard false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' signingConfig signingConfigs.release } } }
6.更改打包的apk名
android{ android.applicationVariants.all { variant -> variant.outputs.all { Date nowTime = new Date() SimpleDateFormat time = new SimpleDateFormat("MM月dd日HH時mm分") outputFileName = "${variant.flavorName}(${variant.versionCode}_${variant.versionName})(${time.format(nowTime)}).apk" } } }
7.引入第三方庫的時候,剔除某些不需要的包或者重複的包
1.直接在configuration中排除 configurations { compile.exclude module: 'commons' all*.exclude group: 'org.gradle.test.excludes', module: 'reports' } 2.在具體的某個dependency中排除 dependencies { implementation("com.github.bumptech.glide:glide:4.8.0") { exclude module: 'appcompat-v7' } }