Android Studio 更新中的问题

        Android Studio 更新时 会提示更新 Android Plugin for Gradle 和 Gradle 为最新版本, 但是对于一些老项目 可是要慎重考虑。

Gradle 和  Android Plugin 之间的关系:

  • Gradle 是一种构建工具  .... 更多的等我学会了再补充
  • 对于Android Studio  使用 Gradle 构建项目,需要使用 Android Plugin  for Gradle 插件来共同协作才能使Android 项目编译成功  而且 两者之间的版本号有一个对应关系,版本号对应上了才能编译成功。


build.gradle详解   

        as 中的所有配置尽在build.gradle 文件中,打包的时候也是解析build.gralde文件来打包的,项目中一般会出现两个build.gradle 文件 ,一个在根目录下,一个在app目录下。

    

app 目录下的build.gradle

  •  apply plugin,声明是Android应用程序还是库模块
  •  android 闭包,配置项目构建的各种属性,compileSdkVersion用于指定项目的编译SDK版本,buildToolsVersion用于指定项目构建工具的版本。

defaultConfig闭包:默认配置,应用程序包名,最小 sdk 版本,目标 sdk 版本,版本号,版本名

buildTypes闭包:指定生成安装文件的配置,是否对代码进行混淆

signingConfigs 闭包:签名信息配置

sourceSets 闭包:源文件路径配置

lintOptions 闭包:lint 配置


另外注意 

 有时候项目会报错,找不到 gradle 2.3.3 这类的问题 可能需要修改一下这里吧

repositories {

// mavenCentral() 该仓库中没有gradle:2.3.3

jcenter()

}

  •  dependencies 闭包,指定当前项目的所有依赖关系,本地依赖,库依赖以及远程依赖
  •  repositories闭包,仓库配置
  1. // 声明是Android程序,  
  2. //com.android.application 表示这是一个应用程序模块,可直接运行  
  3. //com.android.library 标识这是一个库模块,是依附别的应用程序运行  
  4. apply plugin: 'com.android.application'  
  5.   
  6. android {  
  7.     //程序在编译的时候会检查lint,有任何错误提示会停止build,我们可以关闭这个开关  
  8.     lintOptions {  
  9.         //即使报错也不会停止打包  
  10.         abortOnError false  
  11.         //打包release版本的时候是否进行检测  
  12.         checkReleaseBuilds false  
  13.     }  
  14.   
  15.     //编译sdk的版本,也就是API Level,例如API-19、API-20、API-21等等。  
  16.     compileSdkVersion 26  
  17.     //build tools的版本,其中包括了打包工具aapt、dx等等。  
  18.     //这个工具的目录位于你的sdk目录/build-tools/下  
  19.     buildToolsVersion '26.0.2'  
  20.   
  21.     //关闭Android Studio的PNG合法性检查  
  22.     aaptOptions.cruncherEnabled = false  
  23.     aaptOptions.useNewCruncher = false  
  24.   
  25.     defaultConfig {  //默认配置  
  26.         applicationId "com.hebbe.espressotest" //应用程序的包名  
  27.         minSdkVersion 22  //最小sdk版本,如果设备小于这个版本或者大于maxSdkVersion将无法安装这个应用  
  28.         targetSdkVersion 26 //目标sdk版本,充分测试过的版本(建议版本)  
  29.         versionCode 1  //版本号,第一版是1,之后每更新一次加1  
  30.         versionName "1.0" //版本名,显示给用户看到的版本号  
  31.   
  32.         archivesBaseName = "weshare-$versionName" //指定打包成Jar文件时候的文件名称  
  33.         ndk {  
  34.             moduleName "hebbewifisafe"                   //设置库(so)文件名称  
  35.             ldLibs "log""z""m""jnigraphics""android"  
  36.             //引入库,比如要用到的__android_log_print  
  37.             abiFilters "armeabi""x86""armeabi-v7a"      //, "x86"  显示指定支持的ABIs  
  38.             cFlags "-std=c++11 -fexceptions"                // C++11  
  39.             stl "gnustl_static"  
  40.         }  
  41.   
  42.         //当方法数超过65535(方法的索引使用的是一个short值,  
  43.         //而short最大值是65535)的时候允许打包成多个dex文件,动态加载dex。这里面坑很深啊  
  44.         multiDexEnabled true  
  45.   
  46.         //Instrumentation单元测试  
  47.         testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"  
  48.     }  
  49.   
  50.     //默认的一些文件路径的配置  
  51.     sourceSets {  
  52.         main {  
  53.             manifest.srcFile 'AndroidManifest.xml'//指定清单文件  
  54.             res.srcDirs = ['res']//指定res资源目录  
  55.             assets.srcDirs = ['assets']    //asset资源目录  
  56.             jni.srcDirs 'src/main/jni'     //jni代码目录  
  57.             jniLibs.srcDir 'src/main/jniLibs' //jni库目录  
  58.             java.srcDirs = ['src']//指定java源代码目录  
  59.             resources.srcDirs = ['src']//指定resource目录  
  60.             aidl.srcDirs = ['src']//指定aidl目录  
  61.             renderscript.srcDirs = ['src']//指定source目录  
  62.         }  
  63.         debug.setRoot('build-types/debug')//指定debug模式的路径  
  64.         release.setRoot('build-types/release')//指定release模式的路径  
  65.     }  
  66.   
  67.     //multiDex的一些相关配置,这样配置可以让你的编译速度更快  
  68.     dexOptions {  
  69.         //让它不要对Lib做preDexing  
  70.         preDexLibraries = false  
  71.         //开启incremental dexing,优化编译效率,这个功能android studio默认是关闭的。  
  72.         incremental true  
  73.         javaMaxHeapSize "4g"     //增加java堆内存大小  
  74.     }  
  75.   
  76.     signingConfigs {//签名配置  
  77.         release {//发布版签名配置  
  78.             storeFile file("fk.keystore")//密钥文件路径  
  79.             storePassword "123456"//密钥文件密码  
  80.             keyAlias "fk"//key别名  
  81.             keyPassword "123456"//key密码  
  82.         }  
  83.         debug {//debug版签名配置  
  84.             storeFile file("fk.keystore")  
  85.             storePassword "123456"  
  86.             keyAlias "fk"  
  87.             keyPassword "123456"  
  88.         }  
  89.     }  
  90.   
  91.     //指定生成安装文件的配置,常有两个子包:release,debug,注:直接运行的都是debug安装文件  
  92.     buildTypes {  
  93.         //release版本的配置,即生成正式版安装文件的配置  
  94.         release {  
  95.             zipAlignEnabled true  //是否支持zip  
  96.             shrinkResources true  // 移除无用的resource文件  
  97.             minifyEnabled false //是否对代码进行混淆,true表示混淆  
  98.             //指定混淆时使用的规则文件;  
  99.             // proguard-android.txt指所有项目通用的混淆规则,proguard-rules.pro当前项目特有的混淆规则  
  100.             //release的Proguard默认为Module下的proguard-rules.pro文件  
  101.             proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'  
  102.             debuggable false  //是否支持调试  
  103.             //ndk的一些配置  
  104.             ndk {  
  105.                 // cFlags "-std=c++11 -fexceptions -O3 -D__RELEASE__" // C++11  
  106.                 // platformVersion  = "19"  
  107.                 moduleName "hebbewifisafe" //设置库(so)文件名称  
  108.                 ldLibs "log""z""m""jnigraphics""android"  
  109.                 //引入库,比如要用到的__android_log_print  
  110.                 abiFilters "armeabi""x86""armeabi-v7a"//, "x86"  
  111.                 cFlags "-std=c++11 -fexceptions" // C++11  
  112.                 stl "gnustl_static"  
  113.             }  
  114.             //采用动态替换字符串的方式生成不同的release.apk  
  115.             applicationVariants.all { variant ->  
  116.                 variant.outputs.each { output ->  
  117.                     def outputFile = output.outputFile  
  118.                     if (outputFile != null && outputFile.name.endsWith('release.apk')) {  
  119.                         def timeStamp = new Date().format('yyyyMMddHH');  
  120.                         def fileName = "WeShare-${defaultConfig.versionName}" + "-" + timeStamp + "-lj-" + ".apk";  
  121.                         output.outputFile = file("${outputFile.parent}/${fileName}")  
  122.                     }  
  123.                 }  
  124.             }  
  125.             jniDebuggable false  //关闭jni调试  
  126.         }  
  127.         debug {//debug版本的配置  
  128.             minifyEnabled false  
  129.             zipAlignEnabled true  
  130.             shrinkResources true // 移除无用的resource文件  
  131.             proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'  
  132.             debuggable true  
  133. //          jniDebuggable true  
  134.             ndk {  
  135.                 cFlags "-std=c++11 -fexceptions -g -D __DEBUG__" // C++11  
  136.             }  
  137.             jniDebuggable true  
  138.         }  
  139.     }  
  140.   
  141.     packagingOptions  
  142.         {  
  143.             exclude 'META-INF/ASL2.0'  
  144.             exclude 'META-INF/LICENSE'  
  145.             exclude 'META-INF/NOTICE'  
  146.             exclude 'META-INF/MANIFEST.MF'  
  147.         }  
  148.       
  149.     compileOptions {  
  150.         //在这里你可以进行 Java 的版本配置,  
  151.         //以便使用对应版本的一些新特性  
  152.     }  
  153.     productFlavors {  
  154.         //在这里你可以设置你的产品发布的一些东西,  
  155.         //比如你现在一共软件需要发布到不同渠道,  
  156.         //且不同渠道中的包名不同,那么可以在此进行配置;  
  157.         //甚至可以设置不同的 AndroidManifest.xml 文件。  
  158.         hebbe {  
  159.         }  
  160.         googlePlay {  
  161.         }  
  162.         solo {  
  163.         }  
  164.     }  
  165.     productFlavors.all {  
  166.         flavor -> flavor.manifestPlaceholders = [UMENG_CHANNEL_VALUE: name]  
  167.     }  
  168.     //所谓ProductFlavors其实就是可定义的产品特性,  
  169.     //配合 manifest merger 使用的时候就可以达成在一次编译  
  170.     //过程中产生多个具有自己特性配置的版本。  
  171.   
  172.     //上面这个配置的作用就是,为每个渠道包产生不同的 UMENG_CHANNEL_VALUE 的值。  
  173. }  
  174.   
  175. //指定当前项目的所有依赖关系:本地依赖、库依赖、远程依赖  
  176. //本地依赖:可以对本地Jar包或目录添加依赖关系  
  177. //库依赖:可以对项目中的库模块添加依赖关系  
  178. //远程依赖:可以对jcenter库上的开源项目添加依赖  
  179. //标准的远程依赖格式是 域名:组织名:版本号  
  180. dependencies {  
  181.     implementation fileTree(dir: 'libs', include: ['*.jar']) //本地依赖  
  182.     //远程依赖,com.android.support是域名部分,appcompat-v7是组名称,26.1.0是版本号  
  183.     implementation 'com.android.support:appcompat-v7:26.1.0'  
  184.     implementation 'com.android.support.constraint:constraint-layout:1.0.2'  
  185.     implementation project(':hello')//库依赖  
  186.     testImplementation 'junit:junit:4.12' //声明测试用列库  
  187.     androidTestImplementation 'com.android.support.test:runner:1.0.1'  
  188.     androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'  
  189. }  
  190.   
  191. //声明是要使用谷歌服务框架  
  192. apply plugin: 'com.google.gms.google-services'  
  193.   
  194. //第三方依赖库的本地缓存路径  
  195. task showMeCache << {  
  196.     configurations.compile.each { println it }  
  197. }  
  198. //使用maven仓库。android有两个标准的library文件服务器,一个jcenter一个maven。两者毫无关系。  
  199. //jcenter有的maven可能没有,反之亦然。  
  200. //如果要使用jcenter的话就把mavenCentral()替换成jcenter()  
  201. repositories {  
  202.     mavenCentral()  
  203. }  

根目录下的build.gradle

  • repositories闭包,声明了jcenter()的配置
  •  dependencies闭包,声明了一个Gradle插件

[java]  view plain  copy
  1. buildscript {  
  2.       
  3.     repositories {  //repositories闭包  
  4.         google()  
  5.         jcenter() //代码托管库:设置之后可以在项目中轻松引用jcenter上的开源项目  
  6.     }  
  7.     dependencies {  //dependencies闭包  
  8.         classpath 'com.android.tools.build:gradle:3.0.0' ////声明gradle插件,插件版本号为3.0.0  
  9.         //gradle是一个强大的项目构建工具,不仅可以构建Android,还可以构建java,C++等  
  10.         //此处引用android的插件  
  11.         // NOTE: Do not place your application dependencies here; they belong  
  12.         // in the individual module build.gradle files  
  13.     }  
  14. }  
  15.   
  16. allprojects {  
  17.     repositories {  
  18.         google()  
  19.         jcenter() //代码托管库:设置之后可以在项目中轻松引用jcenter上的开源项目  
  20.     }  
  21. }  
  22.   
  23. task clean(type: Delete) {  
  24.     delete rootProject.buildDir  
  25. }  

apply plugin用来指定用的是哪个插件,取值有:

  • com.android.application:Android APP插件(打包得到的是.apk文件)
  • com.android.library:Android库插件(打包得到的是.aar文件)

android用来指定Android打包插件的相关属性,其包含如下节点

  • compileSdkVersion(apiLevel):设置编译时用的Android版本
  • buildToolsVersion(buildToolsVersionName):设置编译时使用的构建工具的版本
  • defaultConfig:设置一些默认属性,其可用属性是buildTypes和ProductFlavors之和
  • sourceSets:配置相关源文件的位置,当你的项目的目录结构跟默认的有区别但又不想改的时候sourceSets就派上用场了

    • aidl 设置aidi的目录
    • assets 设置assets资源目录
    • compileConfigurationName The name of the compile configuration for this source set.
    • java Java源代码目录
    • jni JNI代码目录
    • jniLibs 已编译好的JNI库目录
    • manifest 指定清单文件
    • name The name of this source set.
    • packageConfigurationName The name of the runtime configuration for this source set.
    • providedConfigurationName The name of the compiled-only configuration for this source set.
    • renderscript Renderscript源代码目录
    • res 资源目录
    • setRoot(path) 根目录
  • signingConfigs:配置签名信息

    • keyAlias 签名的别名
    • keyPassword 密码
    • storeFile 签名文件的路径
    • storePassword 签名密码
    • storeType 类型
  • buildTypes:配置构建类型,可打出不同类型的包,默认有debug和release两种,你还可以在增加N种

    • applicationIdSuffix 修改applicationId,在默认applicationId的基础上加后缀。在buildType中修改 applicationId时只能加后缀,不能完全修改
    • debuggable 设置是否生成debug版的APK
    • jniDebuggable 设置生成的APK是否支持调试本地代码
    • minifyEnabled 设置是否执行混淆
    • multiDexEnabled Whether Multi-Dex is enabled for this variant.
    • renderscriptDebuggable 设置生成的APK是否支持调试RenderScript代码
    • renderscriptOptimLevel 设置RenderScript优化级别
    • signingConfig 设置签名信息
    • versionNameSuffix 修改版本名称,在默认版本名称的基础上加后缀。在buildType中修改版本名称时只能加后缀,不能完全修改
    • zipAlignEnabled 设置是否对APK包执行ZIP对齐优化
    • proguardFile(proguardFile) 添加一个混淆文件
    • proguardFiles(proguardFileArray) 添加多个混淆文件
    • setProguardFiles(proguardFileIterable) 设置多个混淆文件
  • productFlavors:配置不同风格的APP,在buildTypes的基础上还可以让每一个类型的APP拥有不同的风格,所以最终打出的APK的数量就是buildTypes乘以productFlavors

    • applicationId 设置应用ID
    • multiDexEnabled Whether Multi-Dex is enabled for this variant.signingConfig Signing config used by this product flavor.
    • testApplicationId 设置测试时的应用ID
    • testFunctionalTest See instrumentation.
    • testHandleProfiling See instrumentation.
    • testInstrumentationRunner Test instrumentation runner class name.
    • versionCode 设置版本号
    • versionName 设置版本名称
    • minSdkVersion(int minSdkVersion) 设置兼容的最小SDK版本
    • minSdkVersion(String minSdkVersion) 设置兼容的最小版本
    • proguardFile(proguardFile) 添加一个混淆文件
    • proguardFiles(proguardFileArray) 添加多个混淆文件
    • setProguardFiles(proguardFileIterable) 设置多个混淆文件
    • targetSdkVersion(int targetSdkVersion) 设置目标SDK版本
    • targetSdkVersion(String targetSdkVersion) 设置目标SDK版本
  • testOptions:设置测试相关属性

    • reportDir 设置测试报告的目录
    • resultsDir 设置测试结果的目录
  • aaptOptions:设置AAPT的属性

    • failOnMissingConfigEntry Forces aapt to return an error if it fails to find an entry for a configuration.
    • ignoreAssets Pattern describing assets to be ignore.
    • noCompress Extensions of files that will not be stored compressed in the APK.
    • useNewCruncher Whether to use the new cruncher.
  • lintOptions:设置Lint的属性

    • abortOnError 设置是否在lint发生错误时终止构建
    • absolutePaths Whether lint should display full paths in the error output. By default the paths are relative to the path lint was invoked from.
    • check The exact set of issues to check, or null to run the issues that are enabled by default plus any issues enabled via LintOptions.getEnable() and without issues disabled via LintOptions.getDisable(). If non-null, callers are allowed to modify this collection.
    • checkAllWarnings Returns whether lint should check all warnings, including those off by default.
    • checkReleaseBuilds Returns whether lint should check for fatal errors during release builds. Default is true. If issues with severity "fatal" are found, the release build is aborted.
    • disable The set of issue id's to suppress. Callers are allowed to modify this collection.
    • enable The set of issue id's to enable. Callers are allowed to modify this collection. To enable a given issue, add the issue ID to the returned set.
    • explainIssues Returns whether lint should include explanations for issue errors. (Note that HTML and XML reports intentionally do this unconditionally, ignoring this setting.)
    • htmlOutput The optional path to where an HTML report should be written.
    • htmlReport Whether we should write an HTML report. Default true. The location can be controlled by LintOptions.getHtmlOutput().
    • ignoreWarnings Returns whether lint will only check for errors (ignoring warnings).
    • lintConfig The default configuration file to use as a fallback.
    • noLines Whether lint should include the source lines in the output where errors occurred (true by default).
    • quiet Returns whether lint should be quiet (for example, not write informational messages such as paths to report files written).
    • severityOverrides An optional map of severity overrides. The map maps from issue id's to the corresponding severity to use, which must be "fatal", "error", "warning", or "ignore".
    • showAll Returns whether lint should include all output (e.g. include all alternate locations, not truncating long messages, etc.)
    • textOutput The optional path to where a text report should be written. The special value "stdout" can be used to point to standard output.
    • textReport Whether we should write an text report. Default false. The location can be controlled by LintOptions.getTextOutput().
    • warningsAsErrors Returns whether lint should treat all warnings as errors.
    • xmlOutput The optional path to where an XML report should be written.
    • xmlReport Whether we should write an XML report. Default true. The location can be controlled by LintOptions.getXmlOutput().
    • check(id) Adds the id to the set of issues to check.
    • check(ids) Adds the ids to the set of issues to check.
    • disable(id) Adds the id to the set of issues to enable.
    • disable(ids) Adds the ids to the set of issues to enable.
    • enable(id) Adds the id to the set of issues to enable.
    • enable(ids) Adds the ids to the set of issues to enable.
    • error(id) Adds a severity override for the given issues.
    • error(ids) Adds a severity override for the given issues.
    • fatal(id) Adds a severity override for the given issues.
    • fatal(ids) Adds a severity override for the given issues.
    • ignore(id) Adds a severity override for the given issues.
    • ignore(ids) Adds a severity override for the given issues.
    • warning(id) Adds a severity override for the given issues.
    • warning(ids) Adds a severity override for the given issues.
  • dexOptions

    • incremental Whether to enable the incremental mode for dx. This has many limitations and may not work. Use carefully.
    • javaMaxHeapSize Sets the -JXmx* value when calling dx. Format should follow the 1024M pattern.
    • jumboMode Enable jumbo mode in dx (--force-jumbo).
    • preDexLibraries Whether to pre-dex libraries. This can improve incremental builds, but clean builds may be slower.
  • compileOptions:设置编译的相关属性

    • sourceCompatibility Language level of the source code.
    • targetCompatibility Version of the generated Java bytecode.
  • packagingOptions:设置APK包的相关属性

    • excludes The list of excluded paths.
    • pickFirsts The list of paths where the first occurrence is packaged in the APK.
    • exclude(path) Adds an excluded paths.
    • pickFirst(path) Adds a firstPick path. First pick paths do get packaged in the APK, but only the first occurrence gets packaged.
  • jacoco:设置JaCoCo的相关属性

    • version 设置JaCoCo的版本
  • splits:设置如何拆分APK(比如你想拆分成arm版和x86版)

    • abi ABI settings.
    • abiFilters The list of ABI filters used for multi-apk.
    • density Density settings.
    • densityFilters The list of Density filters used for multi-apk.

dependencies:配置依赖


打包

build.gradle文件配置完成后,打开终端,进入项目目录下,执行gradle build即可打包,打包结束后在相应module的build/outputs/apk/目录下可以看到.apk文件

如果你是在项目目录下执行的打包命令,那么会对项目中所有的module都打包,进入某个module目录下执行打包命令就只对当前module打包,每个module打包生成的APK都才存放在mudule的build/outputs/apk目录下




猜你喜欢

转载自blog.csdn.net/u011139062/article/details/80076255