Configure Gradle Build

Source: Internet
Author: User
Tags maven central

Building the underlying configuration

Android Studio contains a top-level build file and a build file for each module. The build file, known as Build.gradle, is a plain text file that uses groovy syntax to configure the elements provided by the Android Gradle plugin. In most cases, you only need to edit the module-level build file. For example, the build file for the app module for the Buildsystemexample project is like this:

Apply plugin: ' com.android.application '

android {
    COMPILESDKVERSION 19
    buildtoolsversion  "19.0.0"

    defaultconfig {
        MINSDKVERSION 8
        targetsdkversion 19
        Versioncode 1
        versionname  "1.0"
    }
    buildtypes {
        release {
            Minifyenabled true
            proguardfiles getdefaultproguardfile (' Proguard-android.txt '), ' Proguard-rules.pro '
        }
    }
}

dependencies {
    Compile project (": Lib")
    compile  ' Com.android.support : appcompat-v7:19.0.1 '
    compile filetree (dir: ' Libs ',  include:[' *.jar '])
}

Apply plugin: ' Com.android.application ' is built using Android Gradle plugin. This adds Android-specific build tasks to top-level build tasks, and uses android{...} To specify Android-specific build items.

android{...} Configure all Android-specific builds:

The compilesdkversion item specifies the target of the compilation.

The Buildtoolsversion item specifies what version of the build tool to use. Use the SDK Manager to install multiple versions of the build tool.

Note Always use a version whose major version number is greater than or equal to your compilation target SDK.

Defaultconfig the settings for the dynamic configuration of the element in Androidmanifest.xml. The value in the Defaultconfig will overwrite the value in the manifest file. The values configured on Defaultconfig will be applied to all build variants (build variants) unless the configuration of the build variant overrides these values.

The BuildType element controls how your app is built and packaged. The default build system defines two build types: Debug and release. The Debug build type contains the debugging symbol, and the debug key signature is used. The release build type is not signed by default. In this example, the build file is configured with the release version, using the Proguard.

The dependencies element is outside of the Android element and is behind the Android element. This element declares the dependency of this module. There are dependencies in the chapters.

Note: When you change the build file in your project, Android studio requires project synchronization in order for the import to change the build configuration. Click the "Sync Now" button in the yellow notification bar to sync the changed content.

<!--[if GTE VML 1]><v:shapetype id= "_x0000_t75" coordsize= "21600,21600" o:spt= "" o:preferrelative= "T" path= "[Email protected]@[email protected]@[email protected]@[email protected]@5xe" filled= "F" Stroked= "F" > <v:stroke joinstyle= "miter"/> <v:formulas> <v:f eqn= "if linedrawn pixellinewidth 0"/ > <v:f eqn= "sum @0 1 0"/> <v:f eqn= "sum 0 0 @1"/> <v:f eqn= "prod @2 1 2"/> <v:f eqn= "prod @3 21600 Pixelwidth "/> <v:f eqn=" prod @3 21600 pixelheight "/> <v:f eqn=" sum @0 0 1 "/> <v:f eqn=" prod @6 1 2 "/&gt ; <v:f eqn= "prod @7 21600 pixelwidth"/> <v:f eqn= "sum @8 21600 0"/> <v:f eqn= "prod @7 21600 pixelheight"/> <v:f eqn= "sum @10 21600 0"/> </v:formulas> <v:path o:extrusionok= "F" gradientshapeok= "T" o:connecttype= " Rect "/> <o:lock v:ext=" edit "aspectratio=" T "/> </v:shapetype><v:shape id=" Picture _x0020_1 "O:spid=" _ x0000_i1027 "type=" #_x0000_t75 "alt=" Http://developer.andRoid.com/images/tools/as-gradlesync.png "Style= ' width:415.2pt; Height:70.2pt;visibility:visible;mso-wrap-style:square ' > <v:imagedata src= "file:///c:\users\sunnya~1\ Appdata\local\temp\msohtmlclip1\01\clip_image001.png "o:title=" As-gradlesync "/> </v:shape><! [endif]--><!--[If!vml]--><!--[endif]-->

Figure I. Synchronize the projects in Android Studio.

Claim dependent

The application module for this example declares 3 dependencies:

...  dependencies {  //Module Dependency  Compile project (": Lib")    //Remote binary Dependency  Co Mpile ' com.android.support:appcompat-v7:19.0.1 '    //Local binary dependency  compile Filetree (dir: ' Libs ', in clude:[' *.jar ')  }

Each dependency is described below. The build system adds dependencies of all types "compile" to the compilation path, and eventually hits them into the final package.

Module dependencies

The app module relies on the Lib module. Because as described in "Open an Activity from a Library Module", mainactivity login LibActivity1.

Compile project (": Lib") declares the dependent Lib module. When you build the app module, the build system will assemble the Lib module.

Binary dependency of the transport process

Both the app and Lib modules use the Actionbaractivity class from the Android support library, all of which depend on it.

Compile ' com.android.support:appcompat-v7:19.0.1 ' relies on the version of Android Support library 19.0.1 by specifying MAVEN coordinates. The support library for Android in the warehouse pack of the Android SDK is available. If the SDK you installed does not have this package, download it by using the SDK management tool.

Android Studio uses the MAVEN central repository by default to configure the project. (This configuration is in the top-level build file of the project).

Local binary dependencies

Some modules do not use any of the local system binary dependencies. If you have a module that relies on local binary dependencies, copy the jar file to the <modulename>/libs directory.

Compile Filetree (dir: ' Libs ', include: [' *.jar ']) tells the build system to include the jar file dependencies under the App/libs directory into the compilation path, and ultimately in the final package.

For more dependency information on Gradle, see the Gradle User Guide (Dependency Management Basics).

Run Proguard

Build the system to run Proguard to confuse your code during the build process. In Buildsystemexample, build files that run Proguard Modify the app module for release:

...  Android {  ...  Buildtypes {  Release {  minifyenabled true  proguardfiles getdefaultproguardfile (' Proguard-android.txt '), ' Proguard-rules.pro '}}  ...

Getdefaultproguardfile (' Proguard-android.txt ') gets the default Proguard settings from the installed Android SDK. You can customize the Proguard rule, and Android Studio will add the Proguard-rules.pro file at the root of the module to the module-specific rules.

Identity of the package: application ID

In the Android build system, the ApplicationID attribute is uniquely labeled as the release app package. The application ID is set in the Android node of the Build.gradle file.

Apply plugin: ' Com.android.application '    android {  compilesdkversion  buildtoolsversion "1 9.1 "    defaultconfig {  "com.example.my.app "  minsdkversion  targetsdk Version  versioncode 1  versionname "1.0"  }

Note: ApplicationID can only be specified in the Build.gradle file and can no longer be androidmanifest.xml in the file.

When using build variants, the build system allows you to specify a unique label for each product flavors and build types. The application ID in the build type is added to product flavors as a suffix.

productflavors {  Pro {  ApplicationID = "Com.example.my.pkg.pro"  }  Free {  ApplicationID = "Com.example.my.pkg.free"  }  }    buildtypes {  Debug {  applicationidsuffix ". Debug"  }  }  ....

The package name still needs to be specified in the manifest file. It is used in your source code to relate your R class and solve related Activity/service registration issues.

 Package = "Com.example.app" >

Note: If you have multiple manifests (for example, a product flavor the specified manifest and a build type of manifest), the package name is optional in these manifests. If it is specified again in these manifests, that registration must match the package name of the manifest under the Src/main directory.

For more information about building files and building procedures, see Build System Overview.

Configure signature Settings

Debug and release versions of the app are different in whether the security device can be debugged and how to sign it. The build system uses a default key to sign the debug version, and a known certificate is used in order to avoid password prompts during the build process. The build system does not sign the release version unless you explicitly define a signature configuration. If you do not have a release key, you can install "Signing your Applications" described in the build.

Working with Build variants

This section describes how the build system can help you create different versions of the same application in a project. It was useful when there was a demo and paid version, or you wanted to publish multiple apk for different devices on Google Play.

The build system uses product flavors to create different versions of your app. Each version may have different features and device requirements. The build system also applies build types to different builds, and is packaged and configured into each version. The combination of each product flavor and build type forms a build Variant. The build system generates a different apk for each build variant.

Build variants

This project example contains two default build types (Debug and release), plus two product flavors (demo and full). For more advanced information about using build variants, see "Build System Overview".

Product Flavors

Create a different version for your app:

<!--[if!supportlists]-->1, <!--[endif]--> define the product flavors in the build file

<!--[if!supportlists]-->2, <!--[endif]--> Create additional source paths for each flavor

<!--[if!supportlists]-->3, <!--[endif]--> Add flavor specific source to your project

The next section takes you through every detail of the Buildsystemexample project. Create two flavor in the Buildsystemexample app. A demo flavor and a full flavor. Two flavors shared mainactivity,mainactivity has a button to jump to a new activity- Secondactivity. Secondactivity is different for two flavor, so you should simulate a situation in which the activity in full flavor is more specific than the activity in the demo flavor. At the end of the exercise, you will get different apk flavor different.

defined in the build file Product Flavors

Define two product flavors for the build file in the app module:

...  Android {  ...  Defaultconfig {...}  Signingconfigs {...}  buildtypes {...}  Productflavors {  Demo {  ApplicationID "Com.buildsystemexample.app.demo"  versio             Nname "1.0-demo"  } full  {  ApplicationID "com.buildsystemexample.app.full"  Versionname "1.0-full"}}  ...

The flavor definition of this project supports the same configuration using Defualtconfig. All flavors identical configurations are defined in Defaultconfig, and each flavor can overwrite any default value. The build file above uses the ApplicationID property to assign to each flavor: Since each flavor has created different apps, they should need different package names.

Note: On Google Play, to enable your app to have multiple APK support. Assign the same package name to the variants you use, and give each viant a different versioncode. To differentiate different variants in Google Play, you should assign a different package name to each variant.

for each Flavor add additional source directory

Now you should create the source directory and add secondactivity to the different flavor. Create the source directory structure for the demo flavor:

<!--[if!supportlists]-->1, <!--[endif]--> in the project template, expand Buildsystemexample, and expand the app directory

<!--[if!supportlists]-->2, <!--[endif]--> Right-click Src directory, select New>directory

<!--[if!supportlists]-->3, <!--[endif]--> Use "demo" as the name of the catalogue

<!--[if!supportlists]-->4, <!--[endif]--> Similarly create the following directory:

App/src/demo/java

App/src/demo/res

App/src/demo/res/layout

App/src/demo/res/values

The structure of the directory looks like Figure 1:

<!--[if GTE VML 1]><v:shape id= "Picture _x0020_2" o:spid= "_x0000_i1026" type= "#_x0000_t75" alt= "http/ Developer.android.com/images/tools/as-demoflavordirs.png "Style= ' width:150pt;height:162.6pt;visibility:visible; Mso-wrap-style:square ' > <v:imagedata src= "file:///c:\users\sunnya~1\appdata\local\temp\msohtmlclip1\01\ Clip_image003.png "o:title=" As-demoflavordirs "/> </v:shape><! [endif]--><!--[If!vml]--><!--[endif]-->

Figure one: the Catalogue of demo flavor

Add a different Activity to a different Flavor Medium:

Add Secondactivity to Demo flavor:

<!--[if!supportlists]-->1, <!--[endif]--> in the project template, right-click the app module, select New>activity.

<!--[if!supportlists]-->2, <!--[endif]--> Select Blank Activity, click Next

<!--[if!supportlists]-->3, <!--[endif]--> input activity name: secondactivity

<!--[if!supportlists]-->4, <!--[endif]--> Enter the package name "Com.buildsystemexample.app"

<!--[if!supportlists]-->5, <!--[endif]--> Right-click the Java directory in the App/src/demo directory to select New>package.

<!--[if!supportlists]-->6, <!--[endif]--> input Com.buildsystemexample.xapp

<!--[if!supportlists]-->7, <!--[endif]--> drag secondactivity to App/src/demo/java

<!--[if!supportlists]-->8, <!--[endif]--> Accept the default refactor

Add secondactivity layout files and resource files to the demo flavor

<!--[if!supportlists]-->1, <!--[endif]--> drag activity_second.xml files from ap/src/main/res/layout to app/src/ In Demo/res/layout

<!--[if!supportlists]-->2, <!--[endif]--> Accept the default prompts

<!--[if!supportlists]-->3, <!--[endif]--> copy strings.xml from App/src/main/res to App/src/demo/res

<!--[if!supportlists]-->4, <!--[endif]--> Replace the contents of the String.xml file as follows:

<!--[if!supportlists]-->5, <!--[Endif]--><?xml version= "1.0" encoding= "Utf-8"?>  < resources>  <stringname= "Hello_world" >this is the full version!</string>  </resources>

Note: From now on, you can develop secondactivity separately for each flavor. For example, you can add more properties to the activity of full flavor.

In order for the specified flavor file to work, click on the IDE window of the ZIP build variants and select the flavor you want to use, as shown in Figure 2. Android Studio may show other flavor errors, but this does not affect the build of the output content.

<!--[if GTE VML 1]><v:shape id= "Picture _x0020_3" o:spid= "_x0000_i1025" type= "#_x0000_t75" alt= "http/ Developer.android.com/images/tools/as-buildvariants.png "Style= ' width:210pt;height:113.4pt;visibility:visible; Mso-wrap-style:square ' > <v:imagedata src= "file:///c:\users\sunnya~1\appdata\local\temp\msohtmlclip1\01\ Clip_image005.png "o:title=" as-buildvariants "/> </v:shape><! [endif]--><!--[If!vml]--><!--[endif]-->

Figure 2

Activity from Mainactivity login to the specified flavor

Secondactivity has the same package name in all the flavors, and you can log in with main activity. Edit mainactivity:

<!--[if!supportlists]-->1, <!--[endif]--> edit Activity_main.xml, add a button:

<linearlayout ...> ...  <button  android:id= "@+id/button2"  android:layout_width= "wrap_content"  android:layou t_height= "Wrap_content"  android:text= "@string/button2" android:onclick= "onbutton2clicked"/>
      
       </linearlayout>
      

<!--[if!supportlists]-->2, <!--[endif]--> to add a text caption for the button, and a button event onbutton2clicked

<!--[if!supportlists]-->3, <!--[endif]--> Add the following code in Mainactivity:

Publicvoid onbutton2clicked (view view) {  Intent Intent =newintent (this,secondactivity.class);  StartActivity (intent);  }

<!--[if!supportlists]-->4, <!--[endif]--> Edit manifest file

<manifest ...>  <application ...>  ...  <activity  android:name= "com.buildsystemexample.app.SecondActivity"  android:label= "@stri Ng/title_activity_second ">  </activity>  </application>  </manifest>

Build types

Build types is built to build a package version for each app package. The default debug and release are provided:

...  Android {  ...  Defaultconfig {...}  Signingconfigs {...}  buildtypes {...}  productflavors {...}  Buildtypes {  Release {  minifyenabled false  proguardfiles GETDEFAULTPROGUARDF Ile (' Proguard-android.txt '), ' Proguard-rules.pro '  }  debug {  debuggable true
              }  }  }  ...

Note: Although the Release build type is the default in the Build.gradle file, both the release and debug build types are used in each build.

In this example, product flavors and build types Create a build variants:

Demodebug

Demorelease

Fulldebug

Fullrelease

For this example, you can click on the Build menu of Android Studio or execute the assemble command at the command line.

Note: Build>make project compiles all the source code in the project. Build>rebuild the project option to recompile all the source code.

Different output directories are created for different build variants.

QQ Technology Group 290551701 http://cxy.liuzhihengseo.com/558.html

Configure Gradle Build

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.