Build android application from command line using gradle

Step1: Download gradle

You can download the Zip from gradle downloads page. For this tutorial I have downloaded the binary only version from the link https://downloads.gradle.org/distributions/gradle-3.4-bin.zip.

Step2: Setup gradle

Unzip the folder into a target location(Let's say it is /c/androidprojects/tools/gradle-3.4) and set the following two variables.

If you are using bash, you can use the following two commands.

  1. export GRADLE_HOME=/c/androidprojects/tools/gradle-3.4
  2. export PATH=${PATH}:$GRADLE_HOME/bin

Step3: Add the file "build.gradle" to your project. An example of the file is given below.

buildscript {
    repositories {
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.0'
    }
}
apply plugin: 'com.android.application'
android {
    compileSdkVersion 22
    buildToolsVersion '25.0.2'
}

dependencies {
}

In the above file you are specifying the version of the android-gradle-plugin as 2.2.0. Please note a given plugin version can be used only with a specified gradle version and a specified buiod tool's version. You can find this information on the link https://developer.android.com/studio/releases/gradle-plugin.html

For version 2.2.0 the requirements are given below.

Step4: Add the file "local.properties" and add sdk location to it. An example is shown bellow.

sdk.dir=C\:\\Users\\Tg\\AppData\\Local\\Android\\sdk

Step5:

Add the actual project related code , an example list of files is given below.

  1. ./src/main/AndroidManifest.xml
  2. ./src/main/java/org/hello/HelloActivity.java
  3. ./src/main/res/layout/hello_layout.xml
  4. ./src/main/res/values/strings.xml

Step6: Build the project by executing the following command.

$>   gradle build

You should see the apk getting generated in the location  "./build/outputs/apk/helloworld-debug.apk"

Notes:

  • Available "compileSdkversions" can be found in the path $SDK/platfroms/ 
  • Available build tool versions can be found in $SDK/build-tools/
  • Any missing/required version can be installed with the help of sdk manager.