3.24.2015

Android Studio - ndk and gradle integration

Android Stdio 1.1.0 Gradle 2.2.1+

import org.apache.tools.ant.taskdefs.condition.Os

apply plugin: 'com.android.application'

def getNdkDir(){
    Properties properties = new Properties()
    properties.load(project.rootProject.file('local.properties').newDataInputStream())
    def ndkdir = properties.getProperty('ndk.dir', null)

    if (ndkdir == null)
        throw new GradleException("NDK location not found. " +
                "Define location with ndk.dir in the local.properties file or with an " +
                "ANDROID_NDK_ROOT/NDK_ROOT/NDKROOT/NDK environment variable.")

    if (!ndkdir.endsWith('/'))
        ndkdir = ndkdir + File.separator;

    return ndkdir
}

android {
    compileSdkVersion 21
    buildToolsVersion "22.0.0"

    defaultConfig {
        minSdkVersion 18
        targetSdkVersion 21
    }

    sourceSets.main {
        jniLibs.srcDir 'src/main/libs'
        jni.srcDirs = [] //disable automatic ndk-build call
    }

    task ndkBuild(type: Exec) {
        def ndkDir = getNdkDir()
        def ndkPath
        if (Os.isFamily(Os.FAMILY_WINDOWS)) {
            ndkPath = ndkDir + 'ndk-build.cmd'
        } else {
            ndkPath = ndkDir + 'ndk-build'
        }
        commandLine ndkPath, '-j4', '-C', file('src/main/jni').absolutePath
    }

    tasks.withType(JavaCompile) {
        compileTask -> compileTask.dependsOn ndkBuild
    }

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