JNI programming under Android Studio (introduce external or AS self-compiled so files)

In the recent Android development, the project is gradually migrated from Eclipse to Android Studio. Google does not officially support the development of ndk in Android Studio, but we can use gradle to automatically compile jni.

step

1. Find local.properties in the new project, and add the path of ndk in it (ndk must be above r9):

ndk.dir=E\:\\Android\\ndk-r10d

2. Create a new jni folder in app\src\main, where the c/c++ files to be compiled and Android.mk are stored

3. Add two tasks to the build.gradle in the app: ndkBuild and copyJniLibs. The first task is to perform compilation for ndk, and the second task copies the compiled so library to the jniLibs directory, so that Android Studio is finally packaged When will the so library be packaged in:

copy code
android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"
    defaultConfig {
        applicationId "com.xxx.yyy"
        versionCode 1
        versionName '1.0'
        minSdkVersion 10
        targetSdkVersion 21
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles ('proguard-android.txt')
        }
    }

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

    sourceSets {
        main {
            jni.srcDirs = []
            jniLibs.srcDirs = ['src/main/jniLibs']
        }
    }
}

task ndkBuild(type: Exec) {
    def ndkDir = project.plugins.findPlugin('com.android.application').sdkHandler.getNdkFolder()
    commandLine "$ndkDir/ndk-build.cmd", '-C', 'src/main/jni',
            "NDK_OUT=$buildDir/ndk/obj",
            "NDK_APP_DST_DIR=$buildDir/ndk/libs/\$(TARGET_ARCH_ABI)"
}

task copyJniLibs(type: Copy) {
    from fileTree(dir: file(buildDir.absolutePath + '/ndk/libs'), include: '**/*.so')
    into file('src/main/jniLibs')
}
copy code

 

These two tasks should not be placed in android{}, but outside android{}, otherwise it will not compile. Among them, NDK_APP_DST_DIR is the folder where the compiled library is stored. Set it according to your needs. Here I am the nkd folder under buildDir.

4. Finally compile, Android Studio will automatically execute the two tasks of ndkBuild and copyJniLibs

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325812683&siteId=291194637