Build your Android app with Gradle

Source: Internet
Author: User

Use Gradle to build your Android program preface

Android Gradle plug-ins have finally integrated the confusing code task, and recently, Android Studio was using Gradle to build the project, determined to read all the user guides for Android Gralde build projects, so that Gradle People also use Gradle to build Android projects, so that packaging (note that packaging and building are different) Multiple versions of Android are no longer painful. Finally, off-topic: Cherish Life, stay away from Ant ....

Gradle Build Android History

Android Tools homepage, about February this year when the release of adt21.1, suddenly found on the homepage of the new build System can be used Gradle to build Android projects, as for what Gradle is (since click to see should know. ) 。 Then, looked again roadmap at that time, still does not support Proguard packing, so did not see ...

Recently, Android Studio released, finally Gradle 0.4 also followed out, so, first Gradle learned again, and then Gradle Plugin User Guide also read carefully, according to my personal experience, if you on Gradle Go to see Gradle without knowing. Plugin User Guide may be confused in many places, but it doesn't prevent you from using Gradle to pack Android apps, but you may have a headache if something goes wrong. However, this blog post is to let not gradle can also use Gradle Packaging Android program, because, I also do not understand gradle, so, I have encountered the problem of the solution are listed.

By the way, the reason why the official use of Gradle

    • Domain specific Language (DSL) to describe and manipulate the build logic
    • Build files is Groovy based and allow mixing of declarative elements through the DSL and using code to manipulate the DSL Elements to provide custom logic.
    • Built-in dependency management through Maven and/or Ivy.
    • Very flexible. The allows using best practices, but doesn ' t, its own, the doing things.
    • Plugins can expose their own DSL and their own API for build files to use.
    • Good tooling API allowing IDE integration
Gradle Basic Concepts

First we learn a few gradle footsteps grammar, mastering these grammar, you can be very simple to build a packaged Android project with Gradle. First, let's look at the next most simple Android build.gradle .

Build.gradle
1234567891011121314151617
{        repositories {            mavencentral ()        }        {            ' com.android.tools.build:gradle:0.4 '        }    }    ' Android '    {+        }    

The introduction of English is from the official documents with Gradle, the main behind the Chinese is not the translation, is the supplementary introduction.

buildscript{}

Configures the build script classpath for this project. It's all about setting up a script's run environment

repositories{}

Returns a handler to create repositories which is used for retrieving dependencies and uploading artifacts produced by th E project. The idea is to support Java-dependent Library Management (MAVEN/IVY) for project dependencies. This is also the gradle strong place ...

dependencies{}

The dependency handler of this project. The returned dependency handler instance can be used for adding new dependencies. For accessing already declared dependencies, the configurations can is used. The definition of the dependent package. Support Maven/ivy, remote, local library, also support single file, if the MAVEN library is defined previously repositories{} , use maven dependency (I have not contacted Ivy. ) com.android.tools.build:gradle:0.4 , the gradle will automatically download the appropriate dependencies to the remote repository just by using a similar.

apply plugin:

Declares the type of project that was built, of course it's Android ...

android{}

Set the parameters for compiling the Android project, and next, all of the configurations for our build Android project are done here.

Build a Gradle Android project

First, you want to install Gradle 1.6 and, in the environment variables of the system, all the commands are the default you already have the gradle environment. Also, Android SDK 22 has already been upgraded

There are two ways to build yours with Gradle: (Build.gradle put in the project directory )

    1. Use ADT 22 to export Build.gradle.
    2. Copy the Build.gradle file that someone else has written.
    3. According to Gradle rules, handwritten Android build.gradle files.

Personal recommendation 1, 2 methods ....

An Android Build.gradle basic basic file

Build.gradle
123456789101112131415161718192021222324252627282930313233343536373839
 buildscript {repositories {mavencentral ()} dependencies {Classpath  ' com.android.tools.build:gradle:0.4 '}}apply plugin:  ' Android ' dependencies {        }android {compilesdkversion 17 buildtoolsversion 8 targetsdkversion 17} sourcesets {main {manifest . srcfile  ' androidmanifest.xml ' java.srcdirs = [ ' src '] resources.srcdirs = [ ' src '] aidl.srcdirs = [ ' src '] renderscript.srcdirs = [ ' src '] res.srcdirs = [ ' res '] assets.srcdirs = [ ' assets ']} Instrumenttest.setroot ( ' tests ')}}        

Then on the command line CD to the project directory

Example: CD E:\workplace\andoridGradle

If you are using Gradle to build Android projects for the first time, it is recommended that you first use gradle clean the Android Gradle plugin, as well as related dependencies to download and initialize the environment, if something goes wrong, it is likely that the download timed out, try a few more times, and finally you will see the following prompt:BUILD SUCCESSFUL

The Taskcontainer.add () method has been deprecated and was scheduled to be remove D in Gradle 2.0. Please use the Create () method instead.

: Clean Up-to-date

BUILD Successful

Total time:7.847 secs

By completing the steps above, you can formally build your Android project using Gralde.

Then the gradle build Android project was built with the use of it. If you follow the above steps, you will want to see a build directory in the project directory, which is used Gradle build Android project All for example, structure catalog see appendix.

The final packaged apk is in the build/apk directory. Then, you will find that two apk one is [project name]-debug-unaligned [project name]-release-unsigned

If you know all of the above, then you'll get into the details of how to use Gralde to pack Android APK.

Gralde Packaging parameters

It said a lot of things, actually not attractive to use gradle, if only to build the project, ADT is not more appropriate? If you read the following and feel the same, you don't have to toss the gradle ...

Signature Package

See the Appendix default output release apk is not signed, then we need to sign the very simple, just need to add in android{} Plus can. Full Build.gradle Please click on my gist

Build.gradle
123456789101112131415
{   myconfig{     storefile file ("Gradle.keystore")    Storepassword "Gradle"    keyalias    "Gradle" Keypassword "Gradle"    }}       buildtypes{     release {    signingconfig  signingconfigs.myconfig     }    
Then, run gradle clean gradle build, this time in build/apk you see one more [project name]-release-unaligned, literally I can know, this is just not zipalign optimized version. and [project name]-release is our signature, and Zipalign apk package. # # # #打混淆包 only need to add on the original basis, complete Proguad.gradle code Build.gradle
12345678
buildtypes{   Release {   signingconfig  signingconfigs.myconfig     true     ' Proguard-android.txt '   }} 

gradle clean

gradle build

Dozen multi-Channel packages (Product Flavor)

Now to explain the question in the previous section, the meaning of thetwo apk in the APK directory

Why is there a two apk?

The default Android Gralde plugin defines the two types of apk type debug, release, and these two types of detailed comparison see appendix.

This is the Android Gralde plugin buildTypes{} method generated, the default configuration of the two default template, of course you can also modify, before we are in the modification of the default release of the configuration, let the output release type of the APK, with signature and confusion.

For multi-channel packages, the Android plugin provides a Product Flavor{} configuration named for multi-channel packaging.

For example, my Android app has overseas edition, and the domestic version, and these two versions of the package name is not the same!! (I'll give you two examples of the market to install this idea, you have to pack 100 different markets just a few lines of code things.) )。

All you have to do is android{} Add.

Build.gradle
12345678
productflavors {playstore {packagename=' Com.youxiachai.androidgradle.playstore '}hiapk {packagename=' Com.youxiachai.androidgradle.amazonappstore '}} 

Then gradle clean , gradle build under build/apk you will see a bunch of packages, named format [project name]-[channel name]-release

Just that?

Product Flavor{}Not only can change the name of the package so simple, but also to compile the source directory to switch.

What do you mean? I do not know if you have used friends of the league to do user statistics, if you use the distribution channel analysis, you need to modify Androidmanifest.xml Tim Plus<meta-data android:value="hiapk" android:name="UMENG_CHANNEL"/>

If, you many channels, and then you will be very painful, now with Gradle is very comfortable, you just need to android.sourceSets specify our channel name on line, Android Gradle plugin, will automatically pack!!! For example

Build.gradle
123456789101112131415161718192021
Sourcesets {    Main {        ' androidmanifest.xml '        java.srcdirs = [' src ']        resources.srcdirs = [' Src ']        aidl.srcdirs = [' src ']        renderscript.srcdirs = [' src ']        res.srcdirs = [' res '] Assets.srcdirs = [' Hiapk/androidmanifest.xml '} instrumenttest.setroot (' tests ')}    
And then run gradle clean, gradle build, save time to have a cup of coffee, sleep or something good ... # # # #外部依赖 # # # Android Gradle supports Maven/ivy managed packages for external jar packages, and also supports specifying specific files, as previously mentioned above. The complete Build.gradle gist shown above is also written inside. You need to add the following code: Build.gradle
123
dependencies {compile files (' Libs/android-support-v4.jar ')} 
Conclusion

At this point, for Android Gradle to build Android applications, packaging Android programs, all the knowledge required, as described above, as long as you are serious about reading the above article, for, how to play dependent on the Android Library project package, You can look at the example provided by the German in the appendix, and for build.gradle the code inside you need to 0.2 change it 0.4 . As for the tutorial on running the Android test Case section with Gradle, I feel that I have written it in white (I have written about the Andorid test and recorded the video. , it is estimated that no one will be concerned, so if you are using Gradle for Android test, you can see the official Gradle Manual provided in the appendix.

Extended Reading

For this part of the content, you read and do not read and do not affect your use of Gradle to pack Android items. The good thing about reading is that you can use gradle better.

  • The complete Gradle Plugin User guide inside of which there is a bug is compile files(‘libs/android-support-v4.jar‘) not the compile file(‘libs/android-support-v4.jar‘) tutorial is based on Android gradle0.3, in 0.4 just more confusing packaging, this piece has been added in the article.

  • A German written by Android-gradle-examples

  • dependencies{}More introduction.

  • Debug, release, these two types of default configurations are as follows:

    Property name Default values for debug Default values for Release/other
    debuggable True False
    Jnidebugbuild False False
    Renderscriptdebugbuild False False
    Renderscriptoptimlevel 3 3
    Packagenamesuffix Null Null
    Versionnamesuffix Null Null
    Signingconfig Android.signingConfigs.debug Null
    zipalign False True
  • defaultconfig {} configuration parameter list

    Property Name Default value in DSL object Default value
    Versioncode -1 Value from manifest if present
    Versionname Null Value from manifest if present
    minsdkversion -1 Value from manifest if present
    targetsdkversion -1 Value from manifest if present
    PackageName Null Value from manifest if present
    Testpackagename Null App Package name + ". Test"
    Testinstrumentationrunner Null Android.test.InstrumentationTestRunner
    Signingconfig Null Null
    Runproguard False False
    Proguardfile ' Proguard-android.txt ' or ' proguard-android-optimize.txt ' ' Proguard-android.txt ' or ' proguard-android-optimize.txt '
  • Build Structure Directory

    Tree
    1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 66676869707172737475767778798081828384858687888990
    build/├──apk├──assets│├──debug│└──release├──classes│├──debug││└──com││└──example││└──gradle│└──release│└──com│└──example│└──gradle├──dependency-cache│├──debug│└──release├──incremental│├──aidl││├──debug││└──release│├──dex││├──debug││└──release│├──mergeassets││├──debug││└──release│└──mergeresources│├──debug│└──release├──libs├──manifests│├──debug│└──release├──res│├──All│  │  ├──debug│  │  │  ├──drawable-hdpi│  │   │  ├──drawable-mdpi│  │  │  ├──drawable-xhdpi│   │  │  ├──drawable-xxhdpi│  │  │  ├──layout│  │   │  ├──menu│  │  │  ├──values│  │  │& nbsp; ├──values-sw720dp-land│  │  │  ├──values-v11│  │   │  └──values-v14│  │  └──release││├──drawable-hdpi││├──drawable-mdpi││├──drawable-xhdpi││├──drawable-xxhdpi││├── layout││├──menu││├──values││├──values-sw720dp-land││├──values-v11││└──values-v14│└── rs│├──debug│└──release├──source│├──aidl││├──debug││└──release│├──buildconfig││├──debug│││└──com│││└──example│││└──gradle││└──release││└──com││└──example││└──gradle│├──r││├──debug│││└──com│││└─ ─example│││└──gradle││└── release││└──com││└──example││└──gradle│└──rs│├─ ─debug│└── release└──symbols├──debug└── releasedirectories    
The Final spit Groove

Spit on the trough a bit ... With the ant script (maybe you haven't touched it.) )。 Before you used the ant script to package the APK, you need to pack the different package names, you need to use ant to read AndroidManifest.xml and then regular match replace the inside PackageName parameter. Although the description process is very simple, you really go to write the time you have a pain (for an ant layman, personally feel ant's learning curve is too steep, if it was two years ago, I may also write such an ant script (the year spent a great effort to study for one weeks), however, Because it is seldom used (and then Maven is known). Decisively give up ant, why not use Maven on Android? Because, the Android Maven plugin is unofficial, and now it seems that Maven's XML is really complicated and looks like a headache) *

Build your Android app with Gradle

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.