Building your Android program with Gradle


May 19 2013

Building your Android program with Gradle

Android gradle plugin got obfuscated code task integrated into, coupled with the recent, Android studio is used by gradle to build the project, determined to build Android gralde user guide the project finished, let not using gradle are built using the gradle Android project, make packing (note, packaging and construction different versions of Android no longer painful). Finally, by the way: cherish life, away from the ant....

Android Tools home, probably in February this year released adt21.1, suddenly at home found New Build System is the original gradle can be used to build Android project, what is gradle (since the click in to see should know by now.). Then, he looked at the RoadMap at that time, also does not support the Proguard package, so I didn't see. .

Recently, Android studio released, Finally, gradle 0.4 also follow up, Therefore, The studied gradle, Then Gradle Plugin User Guide also read about, According to my personal experience, If you know nothing of gradle went to see Gradle Plugin User Guide may be a lot of places., But does not prevent you packed with gradle Android Application, Just, Problems, You may be very headache. However, this blog is not gradle can also use gradle package Android program, because, I also don't know gradle, so, I put the solution the problem I met all one one lists.

Affixed by the way the official reason why the use of gradle

First, we study a few paces of gradle grammar, master the grammar, you can be very simple to use gradle to build up Android project. First of all, we look at one of the most simple Android build.gradle.

build.gradle
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
	
buildscript {
       
	 repositories {
            mavenCentral()
        }

        dependencies {
            classpath 'com.android.tools.build:gradle:0.4'
        }
    }

    apply plugin: 'android'

    android {
        compileSdkVersion 17
    }

English introduction from gradle official document, mainly behind the Chinese translation is not added, the. .

buildscript{}

Configures the build script classpath for this project. it is to set the script running environment

repositories{}

Returns a handler to create repositories which are used for retrieving dependencies and uploading artifacts produced by the project. idea is support for Java dependent library management (maven/ivy), used in projects of dependence. This is 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 definition of the configurations can be used. dependent package. Support maven/ivy, remote, the local library, also supports single file, if the previous definition of repositories{}maven library, relies on the use of Maven (I haven't contacted ivy..) Only when the need to use similar to com.android.tools.build:gradle:0.4, gradle will automatically download the corresponding dependence to remote database.

apply plugin:

The statement construction project types, here is Android. .

android{}

The following parameters, set the compile of Android project, all configuration to build Android project we have done here.

First of all, you need to install Gradle 1.6 and, written into the system environment variables, all commands are default you have with good gradle environment. But, has upgraded the Android SDK 22

To use gradle to build you in one of two ways: (build.gradle in the project directory.)

  1. Using ADT 22 derived build.gradle.
  2. Copy the others to write build.gradle file.
  3. According to the rules of gradle, writing Android build.gradle file.

1,2 method for personal recommendation. . . .

One Android build.gradle most basic file

build.gradle
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
buildscript {

    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:0.4'
    }
}

apply plugin: 'android'

dependencies {
}

android {

    compileSdkVersion 17
    buildToolsVersion "17"

    defaultConfig {
        minSdkVersion 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 in the command line CD to the project directory.

For example: CD e:\workplace\andoridGradle

If you are the first to use gradle to build Android projects suggest that you first use the gradle clean the Android gradle plugin, and dependent package download and initialize the environment, if wrong, the general can be download timeout, try several times, finally you will see the following tips: BUILD SUCCESSFUL

The TaskContainer.add() method has been deprecated and is 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

Complete the above steps, we can formally to build your Android project using gralde.

Then use the gradle build completed Android project construction. If you follow the steps above, go, you will want to project directory to see a build directory, which is building a Android project with gradle all such as the directory structure, see Appendix.

The final package of APK under the build/apk directory. Then, you'll find out, the two APK is a [project name]-debug-unaligned [project name]-release-unsigned

If the above you master the words, then it will explain in detail how to use gralde package Android apk.

It says a lot of things, in fact is not attractive to use gradle, if only the construction project, ADT is not more appropriate? If you read the following content, or feel it, you don't need to do gradle. . . . . .

See appendix a default output release APK is not signed, so we need sign is very simple, only need to supplement can be added in android{}. The complete build.gradle please click on my gist

build.gradle
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
signingConfigs {
   myConfig{
     storeFile file("gradle.keystore")
    	storePassword "gradle"
    	keyAlias "gradle"
    	keyPassword "gradle"
    }
}
    
   buildTypes{
     release {
    	signingConfig  signingConfigs.myConfig
     } 
   }
 
Then, run the gradle clean gradle build, in the build/apk you see more than one [project name]-release-unaligned, literally what I can tell, this is no zipAlign optimized version. But the [project name]-release is our signature, and the zipAlign APK package. ### play confused package ### only needs in the original basis plus, complete proguad.gradle code build.gradle
1
2
3
4
5
6
7
8
buildTypes{
   release {
   signingConfig  signingConfigs.myConfig
     runProguard true
     proguardFile 'proguard-android.txt'
   }
}

gradle clean

gradle build

Now to explain a problem, two apk apk directory under the meaning of

Why have two apk?

The default Android gralde plug-in defines two types of apk debug, release, a detailed comparison of the two types of appendix.

This is the Android gralde plugin buildTypes{} method, configured by default two default template, you can also modify, in front of us is to modify the default release configuration, so that the output release type of APK, with signature and confusion.

For multiple channel packet, Android plug-in provides a Product Flavor{} configuration, for multi channel package.

For example, my Android application overseas edition, and the domestic version, but the two version of the package name is not the same!! (I will give two examples of installation market this idea, you have to pack 100 different market just a few lines of code. ).

You only need to add in android{}.

build.gradle
1
2
3
4
5
6
7
8
productFlavors {
	playstore {
			packageName='com.youxiachai.androidgradle.playstore'
	}
	hiapk {
			packageName='com.youxiachai.androidgradle.amazonappstore'
	}
}

Then gradle clean, gradle build, in the build/apk you will see a pile of bags, naming format [project name and have the channel name]-release

That's all?

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

What do you mean? Do not know if you have not used the Allies do user statistics, if, you are using distribution channels analysis, you need to modify the AndroidManifest.xml add on <meta-data android:value="hiapk" android:name="UMENG_CHANNEL"/>

If, you many channels, then you will be very painful, very comfortable, now with the gradle, you only need to specify our channels in the android.sourceSets name, Android gradle plug-in, automatic packing!!! For example

build.gradle
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
sourceSets {
    main {
        manifest.srcFile 'AndroidManifest.xml'
        java.srcDirs = ['src']
        resources.srcDirs = ['src']
        aidl.srcDirs = ['src']
        renderscript.srcDirs = ['src']
        res.srcDirs = ['res']
        assets.srcDirs = ['assets']
    }
        
    hiapk {
      	manifest.srcFile 'hiapk/AndroidManifest.xml'
    }    	
       	playstore {
       		manifest.srcFile 'hiapk/AndroidManifest.xml'
    }
       
	instrumentTest.setRoot('tests')
        
}
Then run the gradle clean, gradle build, save time to have a cup of coffee, sleep what are good... ### external dependence ### Android gradle for the application of external jar package maven/ivy support package, also support the specified file, as has been said above. It demonstrates the complete build.gradle gist which also has written. You need to add the following code: build.gradle
1
2
3
dependencies {
	compile files('libs/android-support-v4.jar')
}

Thus, for the Android gradle building Android applications, packaged Android program, all the knowledge needed, has stated in the above, as long as you are careful look at the above article, for, how to rely on the Android library project package, the Germans see annex provides examples of writing, and for the code inside the build.gradle you need to put 0.2 to 0.4 can be,. As with the gradle running Android test case part of the tutorial, personal feeling to write or write (I wrote about the andorid test related articles, also recorded a video, so have this feeling. ), Is estimated that there will be no attention, so, if you are Android test gradle, see Annex inside the official gradle manual.

For this part, you read and not read, does not affect your use of the gradle package Android project. As for the reading of the advantage that you can make better use of the gradle. .

Spit at. . . Using ant script (you may not contact. . ). In the past when you use the ant script package APK to pack different package name, you need to read and then match replace inside the packagename parameter AndroidManifest.xml ant. . Although the description of the process is very simple, when you really to write you fucking up (for a ant layman, the learning curve for ant personal feeling is too steep, if two years ago for me, may also write this ant script (that took a lot of effort to learn a week), however, because rarely used (later to know Maven. Decisively abandoned the ant, why not use in the Android Maven? Because, Maven plug-in Android unofficial, but now it seems Maven XML is very complex, it looks headache))*

Posted by Adalheid at November 16, 2013 - 3:34 PM