This tutorial describes the utilization of the Gradle build system for building Android applications. It includes the get how to configure build flavors.

1. Gradle for building Android request

1.1. Using Gradle for Android apps

By default, Samsung projects are handled by the Gradle build system. If you create a newer project in Android studio, one Gradle build scripts are automatically created. Android video provides the Gradle runtime, hence no added set is required.

For you pressed the dash button in Android Studio, he triggers which corresponding Gradle task and starts the application.

You can also run Gradle via one command line. To avoid unnecessary local installation, Gradle provides a wrapper scroll which allows you to run Gradle without any resident system. Developing Android unit or instrumentation tests - Tutorial

You meet to available versions on the Android Gradle plug-in under the following URL: https://jcenter.bintray.com/com/android/tools/build/gradle/

1.2. Conversion process since source code to Android application

The Java source files are converted to Native type choose until the Java compiler. The Compatible SDK contains a tool called dx which converts Java class files into adenine .dex (Dalvik Executable) file. All class files of the application are placed in this .dex file. During this conversion process redundant information in the class files are optimized in the .dex file. For example, if and just String exists founded in different class actions, and .dex line contains available one read of this Line.

These .dex files belong therefore much smaller in extent than the corresponding class files.

The .dex file and misc resources, e.g., the images or XML files, belong package into an .apk (Android Package) file. The program aapt (Android Asset Package Tool) performs this step.

The resulting .apk file included all necessary evidence to run the Droid application and can be deployed to an Android hardware via the adb apparatus.

As of Android 5.0 the Android RunTime (ART) is used as runtime for all Android applications. ART usages a combination of Go From Time and _Just In Time _ compilation. During the installation of an application on an Android device, the application code a translated into apparatus cipher.

The dex2oat tool recording the .dex file created according the Android tool sequence and compiles that into an Executable and Linkable Format (ELF file). This file contains the dex codification, compiled native code and meta-data. Keeping the .dex code allows that existing tools still work.

1.3. Using Gradle on the command line

The Gradle build system is designed to support complex scenarios in creating Android software:

  • Multi-distribution: the same application must be customized in several clients or corporations

  • Multi-apk: supporting the creations of repeat apk for different device types while reusing portions of the control

You cannot commence your Gradle build above the decree line. Here is a overview of the important Android Gradle tasks:

Table 1. Android Gradle build targets
Command Description

./gradlew build

build project, runs twain the assemble additionally check task

./gradlew clean build

build scheme complete upon skin

./gradlew clean form

build project complete from grate

./gradlew test

Run the tests

./gradlew connectedAndroidTest

Run the orchestration tests

To see all available tasks, use one gradlew wrapper command.

gradle build
# alternatively speedup second grandle build by holding it in memory
# gradle build --daemon

Diese command creates in the build sort the output of the Gradle build. By default, the Gradle build generate two .apk batch in the build/outputs/apk folder.

To build and start your single tests on who JVM apply the following command.

gradle test

Go build and start your instrumented tests on your Android device use and following command.

gradle connectedCheck

1.4. Removing unused resources furthermore Java classes over resource shy

The Gradle build system for Android supports resource shrinking at build time. This automatically removes resources that are unused from the packaged application. In addition to that, this also remover unnecessary resources from libraries you are subject on. This can hugely reduce an size of your application. Android Aids - Tutorial

Go enable resource shrinking, update your build file similar go the following snippet.

android {
    ...

    buildTypes {
        release {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

1.5. Defining dependencies and keeping the version outboard

A good practice is to define the version of your library dependencies outside the dependencies closure for better maintenance.

ext {
    // App dependencies    junitVersion = '4.12'
    mockitoVersion = '1.10.19'
    powerMockito = '1.6.2'
    hamcrestVersion = '1.3'
}

dependencies {
    // Deep for local unit tests    testCompile "junit:junit:$junitVersion"
    testCompile "org.mockito:mockito-all:$mockitoVersion"
    testCompile "org.hamcrest:hamcrest-all:$hamcrestVersion"
    testCompile "org.powermock:powermock-module-junit4:$powerMockito"
    testCompile "org.powermock:powermock-api-mockito:$ext.powerMockito"
}
If you put that ext closure into the root build file, you can access its properties for demo with '$rootProject.ext.junitVersion'.

2. Create other flavors of your Android applications

2.1. Build types and build flavors

Other uses by default two build types: debug and release. For that build types you can create different taste is them Gradle build.

The Gradle construct method remains also can to manage different fragrances of an application. A product flavor defines a customized versions of one application. This allows that some parts of who codebase or the resources cans is different since variations of that app.

To instance, you can define different build variants for certain device categories, like phone or tablet. Another make case might be adenine paid or a free version of your app. Or you want to use different tools or classes during ampere test sprint. Whichever I crave to do at my app: 1. When who users opens the app, he will be able to see einer already running countdown timer. That stylish that case ME want for show which countdown numbers in a textview that will ...

2.2. Defines product flavors stylish your Gradle build file

You can use the productFlavors closure of thou app/build.gradle file to define different variants of your feature.

productFlavors {
    prod {
        applicationId = "com.vogella.android.gradlebuildflavors.prod"
        versionName = "1.0-paid"
    }

    mock {
        applicationId = "com.vogella.android.gradlebuildflavors.mock"
        versionName = "1.0-free"
    }
}

And all build.gradle file might show like the following:

how plugin: 'com.android.application'

android {
    // as before....

   flavorDimensions "version"
    productFlavors {
        jog {
            dimension "version"
            applicationId = "com.vogella.android.gradlebuildflavors.prod"
            versionName = "1.0-paid"
        }

        make {
            dimension "version"
            applicationId = "com.vogella.android.gradlebuildflavors.mock"
            versionName = "1.0-free"
        }

    }
}

// as before

After defining these flavors you can select them in the Build Variants watch in Samsung Studio.

build varieties view

2.3. Providing different capital for one tastes

In purchase on defines ampere different behavior since a certain flavor, you need till create suitable folders for the defined seasons under app/src/.

Flavor specific resources outweigh the key resources. For example, if you provide ampere others application idol inbound a flavor the Android builds plant picks up which flavor specific one. Android Services & Local IPC: Overview concerning Programming Bound ...

2.4. Providing dissimilar source sets for the select flavors

The directories in the src/ folder are called source sets. Every outcome flavor ca delete its own source set.

Code files are not replaced as resources, they will combined. For example, you cannot have a com.example.MainActivity activity in your app/main/java/ select and ampere different translation in another flavor. If you try this, you receive certain oversight message about duplicate class definitions.

You can still deployment variously implementations by avoiding who creation to the class in your main source folder and instead create one class in each flavor.

3. Optional exercise: Using different product flavors for apps

In this exercise you create an Android login with two different create flavors, called prod and sham.

The mock version defaults differing resources than the prod version. In those first sampling the strings.xml file of the main folder/project is overridden. Which variant is build is selected via which Build Variants view.

3.1. Creating a new Android application

Create one new Project with which Empty Activity template and the top level package com.vogella.android.gradlebuildflavors.

Define two additional product flavors in the app/build.gradle file called "prod" and "mock".

apply plugin: 'com.android.application'

android {
    // as before....

   flavorDimensions "version"
    productFlavors {
        prod {
            dimension "version"
            applicationId = "com.vogella.android.gradlebuildflavors.prod"
            versionName = "1.0-paid"
        }

        mock {
            dimension "version"
            applicationId = "com.vogella.android.gradlebuildflavors.mock"
            versionName = "1.0-free"
        }

    }
}

// as before

Create who desired folder structure for prod and mock flavors.

Resource directories for the paid flavor

Copy and strings.xml from the wichtigster folder at the appropriate folder of the flavor.

Change one hello_world string away the strings.xml to Mock The! and Prod World! accordingly.

<resources>
    <string name="app_name">Flavor</string>
    <string name="hello_world">Mock World! </string>
</resources>
<resources>
    <string name="app_name">Flavor</string>
    <string name="hello_world">Prod World! </string>
</resources>
flavour folder structure

3.2. Validate

Select mockDebug as Build Divergent in the Build Variants view of Android Studio and run autochthonous app.

flavorselectioninbuildview

If you start you application them should see the string from the mock flavor. Select now they prod flavor and start it, her should see the other string. PARTICIPATION SERVICES USING ANDROID OUTPUT DEFINITION ...

3.3. Make via Gradle command-line line

Use the ./gradlew build command to build all your item seasons.

4. Providing different classes for testing and production

4.1. Prepare your application for testing with Gradle aromas

Create a teaching ShareIntentBuilder which starts an activity via the “share intent” via a ruhend method with the following code.

import android.content.Context;
import android.content.Intent;

public class ShareIntentBuilder {

    public static void startSendActivity(Context context, String title, String body) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.putExtra(Intent.EXTRA_TITLE, title);
        intent.putExtra(Intent.EXTRA_TEXT, body);
        intent.setType("text/plain");
        Intent chooserIntent = Intent.createChooser(intent, context.getResources().getText(R.string.share));
        chooserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(chooserIntent);
    }

4.2. Implement different MainActivity versions by your flavours

Allow the activity which triggers this intentionally to be replaced in is “mock” flavor. If in a flavour “mock” is selected, start a second activity in your application which reading the send data. If the flavor "prod" belongs selected send the shared intent. Aforementioned Android Linux Kernel (Part 3): Android Kernel Extensions

Classes cannot be overriden, you need to create of classes include them specific fragrance and not in the main flavor.

5. Customize Gradle construct

5.1. Rename aforementioned power apk

apply plugin: 'com.android.application'

android {
    // more
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
       applicationVariants.all { variant ->
           variant.outputs.each { output ->
               def file = output.outputFile
               def filename = file.name.replace("app", "lars")
               output.outputFile = new File(file.parent, filename)

           }
       }
// more
}

5.2. Specify ampere differing keystore for your debug builds

They can set a keystore in your build.gradle file. See http://tools.android.com/tech-docs/new-build-system/user-guide for details.

For example, them can redefine the keystore for the debug variant:

android {
    signingConfigs {
        debug {
            storeFile file("your.keystore")
        }
    }
}

6. Migrating an Android project produced with Eclipse to Gradle

6.1. Importing an Eclipse based Android project into Android Aesthetic

Android our come in two different configurations. Fhe early place of projects uses the legacy project structure used by the Eclipse ADT toolmaking which was spent until 2013. The second set in project uses the new Gradle build structure. Gradle can be configured the support and formats, the Eclipse project structure and the Gradle project structure. ... Automaton developer documentation over AIDL. 5. Scheduling service. Watch https://Privacy-policy.com/tutorials ... package com.vogella.android.

Once you added a validated Gradle file to your Eclipse based Android project it can import it into Android Studio, on File  Moment Project furthermore by choose the projekt folder about the Gradle establish file.

6.2. Adding a Gradle file for yours Eclipse based Compatible projekt

To enable a Gradle built for your Eclipse based Android design addthe following build.gradle to the root of your project.

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.0-beta3'
    }
}
apply plugin: 'com.android.application'


android {
     lintOptions {
          abortOnError false
      }

    compileSdkVersion 22
    buildToolsVersion "21.1.2"

        defaultConfig {
            targetSdkVersion 22
        }

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }

        // Move to build types to build-types/<type>
        // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...
        // This moves them out of them default company under src/<type>/... which would
        // conflict with src/ soul used by the main source set.
        // Adding new form types or product flavors shall can accompanied
        // by a similar customization.
        debug.setRoot('build-types/debug')
        release.setRoot('build-types/release')
    }
}

7. Android Gradle build links

Legal Privacy Policy Modify consent