Gradle Android Latest Automated compilation script tutorial

Source: Internet
Author: User

Transferred from: http://blog.csdn.net/changemyself/article/details/39927381

First, preface

Gradle is based on the Groovy language and is oriented toward Java applications. Automated building tools based on DSL (domain-specific language) syntax.

I think the above sentence is very official, all you need to know is that gradle can be used in the Android development of multiple project dependencies of the automated compilation script, know this also know that we use its purpose;

Why not use Ant to do automated compilation scripts, because Ant is fast, but maintenance is too inconvenient, with gradle you can talk with the project team colleagues, with Ant's Children do not force maintenance, quickly replaced Gradle Bar.

This article for Gradle Novice or previously used Gradle low version of Friends, because I feel every time Gradle upgrade that script also some pit dad, some API is discarded, but the overall feeling every upgrade to make this tool more rigorous words, easy to use words.

Second, the demo description

Below I will simply write a demo, through this demo program to let everyone how to quickly get started, a more practical example:

The demo program is divided into 2 projects, you can directly practical eclipse to create a new Android project, in fact, I do so, so we look closely

Here, by the way, highlight the environment configuration of the demo project: (It's important, otherwise I'll hang up below, don't blame me for not telling you)

Jdk:c:\program files\java\jdk1.8.0_20(Note: Do not use Jre,gradle will prompt you to use the JDK)

Otherwise the script will prompt the following error:

* What went wrong:execution failed for task ': Appcompat_v7:compilereleasejava ' .> cannot find System Java Compiler. Ensure that is installed a JDK (not just a JRE) and configured your Java_homesystem variable to point to the Accordi ng directory.

android-sdk:d:\dev\adt-bundle-windows-x86-20140702

ANDROID-API:20, android4.4w (note: It's a good habit to do Android development every time you compile with the latest API)

gradle:2.1,(using the latest version, no Zuo no die, be the pit constantly, happy constantly)

Gradle: Http://www.gradle.org/documentation, you can look at the document, of course, your e-text good words, will be easy to use, but it's okay, read the article I wrote you gradle document you can not read, because a lot of things you do not use, Unless you use a particularly complex feature in your project

gradle2.1 API Documentation: Http://www.gradle.org/docs/current/javadoc/org/gradle/api/Project.html, this requires you to occasionally turn over, because the simple function will be used on the

environment variable Configuration :

Java_home,gradle_home are added to the environment variables.

Of course, you have to add Java_home/bin to the path variable, and gradle_home/bin, so that you can open a CMD command line below, before you use the Gradle build command

Well, when the preparations are complete, we'll start talking about the demo project.

The Testdemo project wrote an activity that showed Hello world!

APPCOMPATV7 Engineering Everyone knows a library, very representative, we will use more than one library in the actual project, you can extrapolate.

Here's a look at the catalog file:

You want to run a compile script that requires 2 configuration files, Local.properties and Settings.gradle

The code content in Settings.gradle:

Include ': Appcompat_v7 ', ': Testdemo '

This can be seen in the description of project, if you have a number of projects, such as the main project or reference Library project, you need to declare in this area, otherwise gradle cannot find

The code content in Local.properties:

Sdk.dir=d:\\dev\\adt-bundle-windows-x86-20140702\\sdk

This can be seen in the directory of the Android SDK, fill it out, otherwise it will be error.

All right, let's talk about a build.gradle file that needs to be configured for each project.

The Build.gradle of APPCOMPAT_V7 project:

Buildscript{repositories{mavencentral ();} Dependencies{classpath ' com.android.tools.build:gradle:0.13.+ '}tasks.withtype (javacompile) {options.encoding = " UTF-8 "}}apply plugin: ' Android-library ' Dependencies{compile filetree (dir: ' Libs ', include:" *.jar ")}android{ Compilesdkversion 20buildToolsVersion "Enforceuniquepackagename=falselintoptions{abortonerror false}sourcesets {main{manifest.srcfile ' androidmanifest.xml ' java.srcdirs = [' src ']resources.srcdirs  = [' src ']aidl.srcdirs = [' src ']renderscript.srcdirs = [' src ']res.srcdirs = [' res ']assets.srcdirs = [' Assets ']}}lintoptions{abortonerror false}}

For this file I need to highlight several points:

1, classpath ' com.android.tools.build:gradle:0.13.+ ', many people use a low version out of the problem write what 0.11+, I don't care, you want to use gradle2.1 version, here is written 1.13+ package you are right.

2, Apply plugin: ' Android-library ', explain this one library project, detailed oneself find data brain complement

3, Tasks.withtype (javacompile) {options.encoding = "UTF-8"}, task is a what to find out, here compiled encoding with UTF-8, A little bit in the lower version of the script some people write Tasks.withtype (Compile), so that the error, change to Javacompile bar, I was 1.1 points wrong

4, android{
Compilesdkversion 20
Buildtoolsversion "20"

This is version 20, why? Above you look at my ANDROID-SDK API version will know, write other also can, you have to ensure that your local androidsdk have.

Several documents in the TESTDEMO project:

Build directory: Is the Gradle execution compile time generated, inside a lot of content, have the interest to turn over to see

Output directory: I wrote the script, and finally the APK in the build automatically copy to this directory, this can be specific to see the script

blue_key:apk Signature File

Build.gradle: You know

Build.gradle in the Testdemo project

Import Java.util.regex.pattern//import Com.android.builder.DefaultManifestParserimport Com.android.builder.core.defaultmanifestparserbuildscript{repositories{mavencentral ()}dependencies{classpath ' com.android.tools.build:gradle:0.13.+ '}/***tasks.withtype (Compile) {options.encoding = "UTF-8"}**/tasks.withtype ( Javacompile) {options.encoding = "UTF-8"}}apply plugin: ' Android ' Dependencies{compile filetree (dir: "Libs", include: ' * . Jar ') Compile project (': Appcompat_v7 ')}android{compilesdkversion 20buildToolsVersion "Enforceuniquepackagename =falsedefaultconfig{targetsdkversion 17;} Lintoptions{abortonerror false}dexoptions {predexlibraries = false}packagingoptions {exclude ' META-INF/ DEPENDENCIES.txt ' Exclude ' meta-inf/license.txt ' exclude ' meta-inf/notice.txt ' exclude ' meta-inf/notice ' exclude ' Meta-inf/license ' Exclude ' meta-inf/dependencies ' exclude ' meta-inf/notice.txt ' Exclude ' meta-inf/license.txt ' Exclude ' meta-inf/dependencies.txt ' exclude ' meta-inf/lgpl2.1 ' Exclude ' meta-inf/asl2.0 '}signingconfigS{myconfig{storefile file ("Bluekey") Storepassword "Blue" Keyalias "Blue" Keypassword "Blue"}}buildtypes{release{ Runproguard true//Turn on obfuscation switch proguardfile ' proguard.txt.txt '//configure individual files so signingconfigs.myconfig}}sourcesets{main{ Manifest.srcfile ' androidmanifest.xml ' java.srcdirs = [' src ']resources.srcdirs = [' src ']aidl.srcdirs = [' src ']//  Rendersrcdirs = [' src ']res.srcdirs = [' res ']assets.srcdirs = [' Assets ']}}task copynativelibs (type:copy) {from (new File (Project (': Appcompat_v7 '). Getprojectdir (), ' Libs ') {include ' **/*.so '} into new File (BuildDir, ' native-libs ')}tasks.withtype (javacompile) {compiletask-Compiletask.dependson Copynativelibs}clean.dependson ' Cleancopynativelibs ' Tasks.withtype (com.android.build.gradle.tasks.PackageApplication) {pkgtask- Pkgtask.jnifolders = new hashset<file> () PkgTask.jniFolders.add (New File (BuildDir, ' Native-libs ')}} Build.dolast {def today = new Date (). Format (' YyMMdd '); Copy{//from (' build/apk ') from (' build/outputs/apk ') into (' OUTPUT ') include (' testdemo-debug.apk ') rename (' testdemo-debug.apk ', ' blue-' +today+ '-' +readversion () + '-demo.apk ')}}/** * Read version number from manifest.xml **/def readversion () {def manifestparser = new Defaultmanifestparser () return Manifestparser.getversionname (android.sourceSets.main.manifest.srcFile);}




For this file I need to highlight a few points (important):

1,//import Com.android.builder.DefaultManifestParser
Import Com.android.builder.core.DefaultManifestParser

Commented out code is the lower version of the wording, currently using the latest API

2,/***
Tasks.withtype (Compile) {
options.encoding = "UTF-8"
}
**/

Tasks.withtype (javacompile) {options.encoding = "UTF-8"}

Commented out code is the lower version of the wording, currently using the latest API

3.

dependencies{
Compile Filetree (dir: "Libs", include: ' *.jar ')
Compile project (': Appcompat_v7 ')
}

Compile dependency, we can see the dependent library appcompat_v7 to write here, note ":" (colon must be written)

4.

signingconfigs{
myconfig{
StoreFile file ("Bluekey")
Storepassword "Blue"
Keyalias "Blue"
Keypassword "Blue"
}
}


buildtypes{
release{
Signingconfigs.myconfig
}
}

Compile time signature file configuration, of course, you can also compile debug and unsigned apk, self-check data to

5.

Task Copynativelibs (type:copy) {
From (New File (Project (': Appcompat_v7 '). Getprojectdir (), ' Libs ') {include ' **/*.so '}
Into new File (BuildDir, ' native-libs ')
}



Tasks.withtype (javacompile) {
Compiletask, Compiletask.dependson copynativelibs
}

About dependent so files and jar files, copy relies on the main project's Native-libs directory before compiling

6. Build.dolast {
def today = new Date (). Format (' YyMMdd ');
copy{
From (' build/apk ')
From (' build/outputs/apk ')
Into (' Output ')
Include (' testdemo-debug.apk ')
Rename (' testdemo-debug.apk ', ' blue-' +today+ '-' +readversion () + '-demo.apk ')
}
}

/**
* Read the version number from Manifest.xml
**/
Def readversion () {
def manifestparser = new Defaultmanifestparser ()
Return Manifestparser.getversionname (Android.sourceSets.main.manifest.srcFile);
}

Build.dolast, is the final implementation of the meaning, about Gradle task we need to simply check the data to grasp.

Here's what to note:

def today = new Date (). Format (' YyMMdd ');

def manifestparser = new Defaultmanifestparser ()

All need def declaration variable, the low version does not have to write, but the current does not write will error.

The function of this code is to read the Versioncode from the manifest file and rename the apk file in output with the current date.

Convenient, very practical point.

7, Apply plugin: ' Android '

This means that the script needs to compile an Android project, is it different from the library above? Gradle also supports the compilation of Java project, and you check the data yourself.

Third, compile the execution: below we open the CMD Command window to compile the operation

Perform Gradle build in the Testdemo directory, because this is the root directory where local.properties and Settings.gradle are located.

At the first execution time, gradle downloads the required jar packages based on dependencies, creating a. Gradle directory in each of your projects.

dependencies{
Classpath ' com.android.tools.build:gradle:0.13.+ '
}

After the download is successful

OK, then we're done compiling, gradle build

Compile normal will prompt build successful, and then go to the output directory to find the APK.

Here's a reminder that a jar conflict can cause a compile break:

Because many friends of project's Libs directory has multiple Android-support-v4.jar caused.

Last Wordy

Today, we have to write this, we actually use a lot of needs, such as: automatic according to multi-channel packaging, according to different resources and different pkg apk packaging, gradle can help you fix, this demo later time I posted. What is the problem, you can communicate with me (QQ group: 221057495)。

Iv. References:

After upgrading to Gradle 2.0:could not the Find property ' Compile ' on Root project
Unable to resolve class in Build.gradle using Android Studio 0.60/gradle 0.11

How to configure Build.gradle files of a existing project with Actionbarsherlock Lib?
Multiple settings Gradle files for multiple projects building

Android Tools Project Site

Demo

Gradle2.1demo Tutorials (multiple reviews ha)

Gradle Android Latest Automated compilation script tutorial

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.