Android Studio 和 NDK 集成问题

Android Studio and NDK integration issue

我正在使用 Android NDK 将 C/C++ 代码库构建到共享库中。 NDK 成功构建了代码并生成了 .so 文件。然后我想把预构建的共享库(.so 文件)放到我的 Android Studio 项目中。我使用的 Android Studio 版本是 1.0.1。当我按照 this article 的建议将所有预构建的四个 .so 文件放在 src/main/jniLibs 中的 jniLibs 文件夹下,然后我在 Android Studio 中构建整个项目时,构建失败,因为它报告了一些“C++ STL header not found”错误。

我认为将 .so 文件放在 jniLibs 文件夹下以将 NDK 与 Android Studio 集成一样简单,但事实并非如此。显然 Android Studio gradle 构建系统正在重新编译我的 C/C++ 源代码,即使我已经使用命令行 NDK 构建了共享库。由于 NDK 可以成功构建 C/C++ 代码,Android Studio 不应重新编译代码,而应使用预先存在的 .so 文件。这是 NDK 与 Android Studio 集成中的已知问题吗?如何让 Android Studio 使用预构建的 .so 文件,而不是从它自己的代码中重建 C/C++ 代码?

这是 $PROJECT/app/build.gradle 文件:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "com.example.myapp"
        minSdkVersion 16
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.3'
}

此外,这里是项目根目录 $PROJECT/build.gradle:

中的顶级 build.gradle 文件
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }

}

allprojects {
    repositories {
        jcenter()
    }
}

如何解决这个问题让Android Studio直接使用预建的共享库而不是重新构建C/C++源代码?我认为这可能是由于 Android Studio 和 NDK 中的一个已知问题,或者 Android Studio 使用的 gradle 脚本中有一个技巧可以避免重新编译本机代码。

Android Studio 尚未正式支持 NDK,添加预编译共享 .so 文件时可能会出现一些问题。您可以通过在 build.gradle 文件

上添加此命令来强制 Android Studio 禁用构建您的共享库文件
jni.srcDirs = [] //disable automatic ndk-build call

您还可以包含 Android.mk 和 Application.mk 文件。这是有关如何在 Android Studio https://www.youtube.com/watch?v=0fEtrekNcOo

上构建 NDK 应用程序的详细视频