Quickly learn how to use Gradle in Android Studio

Source: Internet
Author: User
Tags jcenter

Quickly learn how to use Gradle in Android Studio

Gradle is a new generation that can be used for Android development.Build SystemIs also the default build tool for Android Studio.

Gradle scripts are based on a JVM language, Groovy, and DSL (domain-specific language.

Because Groovy is the JVM language, most Java language libraries can be used. DSL is a plug-in specially developed for Android, such as some newMethod),Closure (Closure).

Because Gradle's syntax is concise enough and most java packages can be used, it is well deserved to become a new generation of Build System.

After you create a project using Android Studio, twoBuild. graldeFile, one in the project root directory and the other in the app directory. There is another file --Settings. gradle.

The script file in the root directory isModuleGlobal configuration. All modules contained in its role threshold are configured through settings. gradle.

AppA folder is a module. If a new module is added to the current project --LibTo include the new module in the settings. gralde file.


Basic Structure of gradle script

For example, the content of build. gradle in the root directory is as follows:

// 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:1.0.0-rc4'        // NOTE: Do not place your application dependencies here; they belong        // in the individual module build.gradle files    }}allprojects {    repositories {        jcenter()        maven {            url 'http://mvnrepo.xxx.com/mvn/repository'        }    }}

classpath 'com.android.tools.build:gradle:1.0.0-rc4'Is the Android-specific plug-in. The maven repository is located inJCenter ()This is also the default maven repository. You can also add an additional maven repository address, for example

maven {    url 'http://mvnrepo.xxx.com/mvn/repository'}

Then there is the settings. gradle file:

include ':app'

An app is a module contained in a project. If there are multiple modules, you can add multiple parameters to the include method.


Finally, app/build. gradle

Apply plugin: 'com. android. application 'android {compileSdkVersion 21 buildToolsVersion "21.1.1" compileOptions {sourceCompatibility JavaVersion. version_00007 targetCompatibility JavaVersion. version_00007} defaultConfig {applicationId "your. application. id "minSdkVersion 14 targetSdkVersion 21 versionCode 2 versionName" 2.0.0 "} signingConfigs {release {storeFile file ('release. keystore') storePassword "yourstorepassword" keyAlias "yourkeyalias" keyPassword "yourkeypassword"} debug {storeFile file ('debug. keystore')} buildTypes {release {minifyEnabled true proguardFiles getDefaultProguardFile('proguard-android.txt '), 'proguard-rules. pro 'signingconfig signingConfigs. release} debug {signingConfig signingConfigs. debug} productFlavors {inner {applicationId "your. application. inner. id "versionName" 2.0.0 "} market {}}} repositories {flatDir {dirs 'libs'} dependencies {// General compile name: 'volley', ext: 'aar' compile 'com. nostra13.universalimageloader: universal-image-loader: 1.9.3 'compile 'com. alibaba: fastjson: latest. integration '// project related (Deleted )}

Call the basic syntax of Groovy
apply plugin: 'com.android.application'

In the preceding statementapplyIs a method that passes a parameterplugin,pluginThe value is'com.android.application'.

Multiple parameters are separated by commas (,). For example

compile name: 'volley', ext: 'aar'

Closure

The curly braces in Groovy become a Closure ). For example, the following code

compileOptions {    sourceCompatibility JavaVersion.VERSION_1_7    targetCompatibility JavaVersion.VERSION_1_7}

compileOptionsIs a Method, and its parameter is a closure, which executes two methods in turn --sourceCompatibilityAndtargetCompatibility, All parameters areJavaVersion.VERSION17.

Closures can also be nested

repositories {    flatDir {        dirs 'libs'    }}

Common usage package dependency (aar)
Aar can be used in two cases: ① aar is located in the local directory

First, add the call method repositories in the parameter closure of android.

repositories {    flatDir {        dirs 'libs'    }}

Then add it to the dependencies parameter closure.

compile name: 'volley', ext: 'aar'
② Aar is located in a remote warehouse

Maven is used as an example. Other types of warehouses can also be used, for exampleIvy.

You only need to add@aarYou can.

compile 'com.alibaba:fastjson:latest.integration@aar'

Package dependency (jar)
compile group: 'com.alibaba', module: 'fastjson', version: 'latest.integration'

Can be abbreviated

compile 'com.alibaba:fastjson:latest.integration'

latest.integrationYou can replace it with a specific version number. Here, you can get the latest version on the server.

Remove repeated Dependencies
compile 'com.alibaba.fastjson.latest.integration' {    exclude module: 'annotations', group: 'com.google.android'}

Use Java 7
compileOptions {    sourceCompatibility JavaVersion.VERSION_1_7    targetCompatibility JavaVersion.VERSION_1_7}

ProductFlavors

For different APP distribution channels, we can define differentProduct flavor. You can also defineInternal versionAndExternal versionThe internal version contains some debugging code, which will not be compiled into the final APP at the time of release. You can also specify different internal and external versions.ApplicationIdIn this way, two versions can be installed on the same device at the same time to facilitate debugging.

Execute the Gradle script on the command line.

A shell script is automatically generated under the root directory of the Android project-GradlewBefore Execution, remember to add the x Attribute-chomod +x gradlew

The gradle script contains manyTaskYou can use the task name to specify the task to be executed.

./Gradlew build./gradlew assemble./gradlew assembleInnderDebug Summary

I have to say that Gradle is really easy to use! Although Gradle can be used with Ant or maven, its simplicity and functionality far exceed the other two. Maven is widely used in projects I have developed. I don't know why. When Gradle is used, I often encounter problems where remote dependency packages cannot be obtained, the simplest solution is to download the dependent package locally.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.