How to use my own Android.mk file with Android Studio

yes, by default the gradle android plugin regenerates and uses its own Android.mk file to compile your sources.

You can deactivate this and use your own Android.mk file instead, by setting this inside your build.gradle configuration file:

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

    sourceSets.main {
        jniLibs.srcDir 'src/main/libs' //set libs as .so's location instead of jniLibs
        jni.srcDirs = [] //disable automatic ndk-build call with auto-generated Android.mk
    }

    // call regular ndk-build(.cmd) script from app directory
    task ndkBuild(type: Exec) {
        if (Os.isFamily(Os.FAMILY_WINDOWS)) {
            commandLine 'ndk-build.cmd', '-C', file('src/main').absolutePath
        } else {
            commandLine 'ndk-build', '-C', file('src/main').absolutePath
        }
    }

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

Note that if you only need to pass your own cflags to the auto-generated Makefile, you can set these inside the cFlags "" property to set inside android { ndk {}}

Leave a Comment