Summary of daily development skills of Gradle

Summary of daily development skills of Gradle

Gradle is the default build system in Android Studio. Gradle uses Groovy as the main scripting language. The build.gradle file of our app project and the build.gradle file in the APP Moudle is a Groovy class. Next, let me introduce the basic functions and advanced techniques of Gradle.

Basic Usage

  1. apply plugin: 'com.android.application'  
  2.  
  3. android {
  4. compileSdkVersion 26
  5. buildToolsVersion "26.0.0"  
  6. defaultConfig {
  7. applicationId "com.renny.gradletest"  
  8. minSdkVersion 17
  9. targetSdkVersion 26
  10. versionCode 1
  11. versionName "1.0"  
  12. testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"  
  13. }
  14. buildTypes {
  15. release {
  16. minifyEnabled false  
  17. proguardFiles getDefaultProguardFile( 'proguard-android.txt' ), 'proguard-rules.pro'  
  18. }
  19. }
  20. }
  21.  
  22. dependencies {
  23. compile fileTree(dir: 'libs' , include: [ '*.jar' ])
  24. androidTestCompile( 'com.android.support.test.espresso:espresso-core:2.2.2' , {
  25. exclude group : 'com.android.support' , module: 'support-annotations'  
  26. })
  27. compile 'com.android.support:appcompat-v7:26.+'  
  28. compile 'com.android.support.constraint:constraint-layout:1.0.2'  
  29. testCompile 'junit:junit:4.12'  
  30. }

The code above is the build.gradle file in the default module created by the studio when the Android project is just built. The Gradle version used is 2.3.3. Most of the Gradle function configurations are also implemented in this file.

apply plugin:: is used to specify which plugin to use. Common values ​​in development are

'com.android.application': Android APP plug-in (the packaged file is .apk file)

'com.android.library': Android library plug-in (the packaged file is .aar file)

'java': ordinary java plug-in (packaged as a .jar file)

android{} is used to specify the relevant properties of the Android packaging plug-in, which contains the following nodes

compileSdkVersion(apiLevel): Set the Android version used for compilation

buildToolsVersion(buildToolsVersionName): Set the version of the build tool used when compiling

defaultConfig: Set some default properties. The available properties are the sum of buildTypes and productFlavors. (productFlavors is not included in the default file and will be introduced later.)

buildTypes: Configure the build type, which can generate different types of packages. The most common ones are debug and release. Of course, you can add N more.

productFlavors: Configure different styles of APP. On the basis of buildTypes, each type of APP can have different styles. Therefore, the number of APKs that can be printed is buildTypes multiplied by productFlavors. The variable name of the build is productFlavors+buildTypes.

Dependencies: Configure dependencies. This is definitely the most convenient part after switching from Eclipse to Studio. Various external dependencies can be handled with one line of code without manually downloading dependency packages.

Here compile fileTree(dir: 'libs', include: ['*.jar']) means to depend on all jar files in the libs directory.

Advanced Usage

Well, the basic configuration above is just a simple usage of Gradle. In fact, we can use Gradle to do a lot of tricks.

manifest dynamic configuration

Many third-party SDKs require you to configure some key information in AndroidManifest.xml. Take Umeng Push as an example:

  1. <meta-data
  2. android:value= "YOUR_APP_KEY"   
  3. android: name = "UMENG_APPKEY" />

But the keys of your different test packages and official packages are different, so you can modify them like this:

  1. <meta-data
  2. android: name = "UMENG_APPKEY"  
  3. android:value= "${UMENG_APPKEY}" />

Then add different information to each version in productFlavors, so that the appkey used by different packages you type will be different.

  1. manifestPlaceholders = [UMENG_CHANNEL: "0" ,
  2. UMENG_APPKEY : "123456789" ]

Not only can these custom metadata be dynamically configured, but also the android:icon, android:label and other tags can be modified, so that different packages can have different icons, which is convenient for distinguishing them.

Moudle dynamic dependency

In a componentized app, we may need to depend on different components in the test package and the production package. For example, the test environment needs a debug module, but the production environment does not. Suppose productFlavors is as follows, and the debug module name is module-test.

  1. productFlavors {
  2. ceshi{
  3. }
  4. publish{
  5. }
  6. }

Then you can depend on the test module in dependencies:

  1. ceshiCompile project( ':module-test' )

The same buildTypes are also applicable, both can be used together or separately:

  1. debugCompile project( ':module-test' ) ceshidebugCompile project( ':module-test' )

Reading variables in code

The above functions are all configured separately by gradle, but we often have different requirements for different build packages that need to be reflected in the code: log printing, Toast, etc.

Although the BuildConfig.DEBUG field can be used for judgment, we can use buildConfigField to pass custom values ​​to the code. For example, different build packages require different API addresses starting with Host, different https certificate paths, etc. The usage is:

  1. buildConfigField 'type' , 'name' , '"vaule"'  

for example:

  1. defaultConfig {
  2.  
  3. buildConfigField 'String' , 'author' , '"renny"'  
  4.  
  5. }

The above is added to defaultConfig, and adding it to buildTypes or productFlavors will result in different values ​​in different build versions. If you configure different applicationIds, you can install different build versions of apps on the same phone at the same time.

  1. productFlavors {
  2. ceshi{
  3. applicationId "com.renny.test"  
  4. buildConfigField "String" , "API_TEST" , "http://test.renny.com/android"  
  5. }
  6. publish{
  7. applicationId "com.example.publish"  
  8. buildConfigField "String" , "API_PUBLISH" , "http://publish.renny.com/android"  
  9. }
  10. }

After the above introduction, you may find that buildTypes and productFlavors are very similar in definition, but the difference is that changing buildType will not change the application code, they just handle different things, you can get more technical details through buildType (for example: build optimization, log level, etc.), but the content of the app will not change, on the contrary, using productFlavor configuration can change the content of the app (ps: the content can be imagined as a package, buildType cannot change the applicationId).

Gradle tasks

Gradle tasks are suitable for completing some tedious and error-prone repetitive manual work, such as batch modification, copying, and renaming files.

For example, the applicationVariants.all task can set various properties for each build version, such as changing the name of the APK generated by each build version:

  1. applicationVariants. all { variant ->
  2. variant.outputs.each { output ->
  3. output .outputFile = new File(
  4. output .outputFile.parent,
  5. ( "app-${variant.buildType.name}" + "-" + new Date ().format( 'yyyyMMdd' ) + ".apk" ).toLowerCase())
  6. }
  7. }

By default, gradle will match and generate a build version of each productFlavors*buildTypes. If you want to skip some of them, you can do this:

  1. variantFilter { variant ->
  2. if (variant.buildType. name .equals( 'release' )) {
  3. variant.setIgnore(!variant.getFlavors().get(1). name .equals( 'ceshi' ));
  4. }
  5. if (variant.buildType. name .equals( 'debug' )) {
  6. variant.setIgnore(variant.getFlavors().get(1) .name .equals( 'ceshi' ));
  7. }
  8. }

<<:  Teach you step by step to publish your own CocoaPods open source library

>>:  Swift Practice: Using CoreData to Complete an Address Book Storage

Recommend

How to arrange external links on a website to achieve obvious results?

What kind of external link strategy can have obvi...

Are those health supplements that young people are flocking to really worth taking?

“Can health supplements help young people stay he...

Paying for knowledge, where is your path?

Introduction : What is knowledge payment? What is...

5 user growth strategies from attracting new users to awakening them!

I will share my data operation experience in the ...

Do you have a deep understanding of these basic iOS interview questions?

[[155118]] This is the record of my interview wit...

[Creative Cultivation Program] The "Growth History" of a Little Strawberry

When it comes to strawberries, everyone should be...

A big pot of 10 H5 front-end frameworks

As a siege fighter who has been working on the fr...

How to get users to voluntarily forward and recommend your products?

To promote more effective sales conversion of pro...

Tips for increasing followers through short video operations!

1. Current status of short video development Shor...