Mastering Android NDK
上QQ阅读APP看书,第一时间看更新

Creating a Gradle-based application template manually

Gradle is a more versatile Java building tool compared to Ant, which lets you handle external dependencies and repositories with ease.

Note

We recommend that you watch this video from Google available at https://www.youtube.com/watch?v=LCJAgPkpmR0 and read this official command-line building manual available at http://developer.android.com/tools/building/building-cmdline.html before proceeding with Gradle.

The recent versions of Android SDK are tightly integrated with Gradle, and Android Studio is built using it as its build system. Let's extend our previous 1_AntApp application to make it buildable with Gradle.

First, go to the root folder of the project, and create the build.gradle file with the following content:

buildscript {
  repositories {
    mavenCentral()
  }
  dependencies {
    classpath 'com.android.tools.build:gradle:1.0.0'
  }
}
apply plugin: 'com.android.application'
android {
  buildToolsVersion "19.1.0"
  compileSdkVersion 19
  sourceSets {
    main {
      manifest.srcFile 'AndroidManifest.xml'
      java.srcDirs = ['src']
      resources.srcDirs = ['src']
      aidl.srcDirs = ['src']
      renderscript.srcDirs = ['src']
      res.srcDirs = ['res']
      assets.srcDirs = ['assets']
    }
  }
  lintOptions {
    abortOnError false
  }
}

After this, run the command gradle init. The output should be similar to the following:

>gradle init
:init
The build file 'build.gradle' already exists. Skipping build initialization.
:init SKIPPED
BUILD SUCCESSFUL
Total time: 5.271 secs

The subfolder .gradle will be created in the current folder. Now, run the following command:

>gradle build

The tail of the output should look as follows:

:packageRelease
:assembleRelease
:assemble
:compileLint
:lint
Ran lint on variant release: 1 issues found
Ran lint on variant debug: 1 issues found
Wrote HTML report to file:/F:/Book_MasteringNDK/Sources/Chapter1/2_GradleApp/build/outputs/lint-results.html
Wrote XML report to F:\Book_MasteringNDK\Sources\Chapter1\2_GradleApp\build\outputs\lint-results.xml
:check
:build
BUILD SUCCESSFUL
Total time: 9.993 secs

The resulting .apk packages can be found in the build\outputs\apk folder. Try installing and running 2_GradleApp-debug.apk on your device.