In my case, I'm on Windows and following the answer by Cameron above only works if you use the full name of the ndk-build which is ndk-build.cmd. I have to clean and rebuild the project, then restart the emulator before getting the app to work (Actually I imported the sample HelloJni from NDK, into Android Studio). However, make sure the path to NDK does not contain space.
Finally, my build.gradle is full listed as below:
apply plugin: 'com.android.application'
android {
compileSdkVersion 21
buildToolsVersion "21.1.2"
defaultConfig {
applicationId "com.example.hellojni"
minSdkVersion 4
targetSdkVersion 4
ndk {
moduleName "hello-jni"
}
testApplicationId "com.example.hellojni.tests"
testInstrumentationRunner "android.test.InstrumentationTestRunner"
}
sourceSets.main {
jni.srcDirs = [] // This prevents the auto generation of Android.mk
// sourceSets.main.jni.srcDirs = []
jniLibs.srcDir 'src/main/libs' // This is not necessary unless you have precompiled libraries in your project.
}
task buildNative(type: Exec, description: 'Compile JNI source via NDK') {
def ndkDir = android.plugin.ndkFolder
commandLine "$ndkDir/ndk-build.cmd",
'-C', file('src/main/jni').absolutePath, // Change src/main/jni the relative path to your jni source
'-j', Runtime.runtime.availableProcessors(),
'all',
'NDK_DEBUG=1'
}
task cleanNative(type: Exec, description: 'Clean JNI object files') {
def ndkDir = android.plugin.ndkFolder
commandLine "$ndkDir/ndk-build.cmd",
'-C', file('src/main/jni').absolutePath, // Change src/main/jni the relative path to your jni source
'clean'
}
clean.dependsOn 'cleanNative'
tasks.withType(JavaCompile) {
compileTask -> compileTask.dependsOn buildNative
}
}
dependencies {
compile 'com.android.support:support-v4:21.0.3'
}