對於AndroidStudio下的項目結構可以參考這篇博文AndroidStudio工程結構及gradle介紹。
其中最重要的是主模塊(通常是app)下的build.gradle文件,下面貼出我做過的一個項目的完整gradle文件:
apply plugin: 'com.android.application'
android {
compileSdkVersion 19
buildToolsVersion "21.0.2"
compileOptions{
sourceCompatibility org.gradle.api.JavaVersion.VERSION_1_7
targetCompatibility org.gradle.api.JavaVersion.VERSION_1_7
}
lintOptions {//在build apk 時Android Lint產生的錯誤不會導致中斷生成APK
abortOnError false
}
packagingOptions {
exclude 'META-INF/LICENSE.txt'
}
defaultConfig {
applicationId "cn.llzg.plotwiki"//下面這些原本在Manifest.xml中配置的東西都轉移到了這裏
minSdkVersion 11
targetSdkVersion 21
versionCode 26
versionName "3.2.0"
manifestPlaceholders = [ CHANNEL_NAME:"plotwiki"]//默認的渠道配置
}
signingConfigs{
release{
storeFile file("plotwiki.keystore");
storePassword "plotwiki"
keyAlias "plotwiki"
keyPassword "plotwiki"
}
debug{
storeFile file("plotwiki.keystore");
storePassword "plotwiki"
keyAlias "plotwiki"
keyPassword "plotwiki"
}
}
buildTypes {
release {
minifyEnabled false//proguard的開關
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.release
}
debug{
signingConfig signingConfigs.debug
}
}
productFlavors {//多渠道的配置,可以查看AndroidManifest.xml中的meta-data參考
yingyongbao {
manifestPlaceholders = [ CHANNEL_NAME:"YINGYONGBAO"]
}
umeng {
manifestPlaceholders = [ CHANNEL_NAME:"UMENG" ]
}
wandoujia {
manifestPlaceholders = [ CHANNEL_NAME:"WANDOUJIA" ]
}
anzhuo{
manifestPlaceholders=[CHANNEL_NAME:"anzhuo"]
}
qihu360{
manifestPlaceholders=[CHANNEL_NAME:"360"]
}
xiaomi{
manifestPlaceholders=[CHANNEL_NAME:"xiaomi"]
}
jiuyi{
manifestPlaceholders=[CHANNEL_NAME:"91"]
}
}
}
tasks.withType(JavaCompile) {
options.encoding = "UTF-8"
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile project(':cropper')
compile files('libs/alipaysdk.jar')
compile files('libs/alipayutdid.jar')
compile files('libs/alipaysecsdk.jar')
compile files('libs/android-support-v4.jar')
compile files('libs/jsoup-1.8.1.jar')
}
其中遇到的一些問題有
- .多渠道打包,這個問題可以參考這篇文章:gradle解決多渠道打包apk,我在這裏用的是後一種方法,這樣更容易管理
- 生成release版本的apk時總出現missingTranslation的錯誤導致無法生成apk,這裏在android節點下加lintOption並配置好abortOnError就可以正常生成release的apk了
- 中文亂碼,這個記不清當時怎麼解決了,總之在加上tasks.withType那一小段指定編碼肯定是不會錯的
- 代碼混淆,可以參考buildType節點裏面的release
- jdk版本,可以在android節點下配置compileOptions來實現,我試過改爲jdk1.8,然後代碼裏面就可以用lamda表達式之類的新特性了,但是,不知怎麼回事生成apk時總報錯,搜索這個問題卻找不到資料最後只好做罷,希望有知道解決方案的同學能分享出自己的解決方法